简体   繁体   中英

Best method for appending new column in tab delimited csv file

How can I read and write at the same time in csv file.

def read_txt_file(txt_filename):

def get_all_sheet_values(filename):
    lines = []
    myFile= open( filename, "rU" )
    for aRow in myFile:
        val =  aRow.split('\t')
        val = map(lambda s: s.strip(), val)
        if len(val) > 1 :
            print val
            lines.append(val)
    myFile.close()
    return lines

files_dict = get_all_sheet_values(txt_filename)
return files_dict

So basically this code works file.

my problem is writing to the same csv file. example,

10 10 10 10 10 \n
11 11 11 11 11  \n
22 22 22 22 22  \n

so after iterating each row I have to add status to it.

10 10 10 10 10 correct time1 \n
11 11 11 11 11 wrong   time2  \n
22 22 22 22 22 correct time3  \n

thanks.

Files don't work that way. Write to a new file, and rename it after.

You can't. When you add the column you are making each line longer. If you were to write it out before going to the next line you would overwrite a portion of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM