Skip to content Skip to sidebar Skip to footer

Why Does Python 2.7.3 Think My .csv Document Is All On One Line?

I'm new to programming and I encountered a problem in some of my coursework that I can't make any sense of. Consider an imaginary file called 'example.csv' with the following conte

Solution 1:

Your file is using \r as line separators (also known as the "CR" or "Classic Mac" newline convention). Python's open doesn't deal with this by default.

You can use "universal newlines" mode ('rU' mode in open) to open the file properly.

(Note that some Mac text editors still use \r as the line terminator, though these are thankfully much less common now than they were a few years ago.)

Solution 2:

Your input file is poorly formatted. On Linux, lines are separated by '\n'. On Windows, lines are separated by '\r\n', but code in the runtime library makes the '\r' disappear.

In your file, the lines are separated by '\r', which is not a standard in any modern operating system. Perhaps the program that created the file is flawed in some way.

Solution 3:

if you're dealing with csv you should use the csv module, it takes care of most of the crap involved with processing csv input/output.

import csv
withopen("example.csv", "rb") as infile:
    reader = csv.reader(infile)
    for row in reader:
        print row # a list of items in your file

The with statement hear will automatically close the file for you when you drop out of the statement block.

Post a Comment for "Why Does Python 2.7.3 Think My .csv Document Is All On One Line?"