shartshooter
shartshooter

Reputation: 1811

Beginner: Python - iterating through rows of csv, append result

I'm trying to input data from a csv and run that through a simple function and return it to the same CSV but appended onto the end of the row.

I'm having a hard time understanding the difference between the various modes(r, r+, a+, etc).

I've read the documentation but as a beginner am not understanding quite what they mean and which one is the right for me to be using in this case.

def appendCurrentTime():
    with open("file.csv", "??") as myfile:  #Opens File
        reader = csv.reader(myfile)         
        for row in reader:                  #Runs through each row
            myfile.write(current_time(row[1])) #appends the time, pulling in row[1] into current_time

**Also posting code for the first time, sorry if it doesn't come through clearly.

Upvotes: 0

Views: 603

Answers (2)

wizzard0
wizzard0

Reputation: 1928

Looking at your code, the main problem is that the CSV file is not a "database", so you can't modify a row in the middle without corrupting the next row.

So, open the source file in "rb" mode and destination file in "wb" mode, and AFTER you processed the whole file - delete original and rename new file to the original name.

And, description for the cases you specified:

"r" - open text file for reading, starting from the beginning.
"r+" - open text file for reading and writing, starting from the beginning.
"a+" - create file if not exists; then open as a text file for reading and writing, starting from the end of file, plus you can only write to the end of the file.

In short, "R" means Read, "W" write, "+" - "and other way around", "B" - binary, absense of "B" means text. "A" differs from "W" in that "W" clears the file contents when you call open.

IMHO you should probably open files in binary mode most of the time, even if they are logically "text", to prevent unintended conversions of special characters (especially important with Unicode). So, I would recommend "wb" to "write new file", "rb" to "read existing" and "ab" to "append to existing file" e.g. a log file.

For even more information, read the documentation for the POSIX fopen function - Python tries to adhere to its semantics as much as possible, even on Windows systems.

Upvotes: 1

Thomas Farvour
Thomas Farvour

Reputation: 1103

Since it is a CSV file and implied text, the "rU" flag would be appropriate. The r flag means read and U is universal line terminator mode. This way it won't matter if the file is using Windows, Mac or Unix line terminators.

Also take a look into the Sniffer provided by the CSV library. It will automatically detect most dialects for you and can be passed into the reader function.

http://docs.python.org/2/library/csv.html#csv.Sniffer

Upvotes: 0

Related Questions