简体   繁体   中英

How to write a value in each row of a csv file?

I calculate a value for each row of a csv file with a loop and want to write this value as a new column in each row.

I open the file:

with open('hello.csv', 'r', encoding="latin-1") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    list1 = list(readCSV)

Then loop through the rows and calculate a new value:

for j in list1:
    dt=j[1]
    dt2=dt+1

How can I write dt2 in each row "j" as a new column in the existing csv file "hello.csv"?

Copy from comment:

This was just a simple example. I have convert a data time object to the right time zone:

dtstr=j[1] #string 
hours, minutes = [int(t) for t in tstr.split(':')] 
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + 
              timedelta(hours=hours+4, minutes=minutes)

Use python csv module and create a new column and write row in outfile with new list added with new_column_value .

with open('hello.csv', 'r', encoding="latin-1") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    with open('helloout.csv', 'w', encoding="latin-1") as outfile:
        outCSV = csv.writer(outfile,delimiter=',')
        for line in readCSV:
            new_column_value = func(line[j]) # Your modification function j column number
            new_line = line + [new_column_value]
            outCSV.writerow(newline)
 with open('hello.csv', 'r', encoding="latin-1") as csvfile:
          readCSV = csv.reader(csvfile, delimiter=',')
          list1 = list(readCSV)
          for j in list1:
              dtstr=j[1] #string
              hours, minutes = [int(t) for t in tstr.split(':')]
              dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S')         +timedelta(hours=hours+4, minutes=minutes)
              with open('hello out.csv', 'w', encoding="latin-1") as outfile:
                    outCSV = csv.writer(outfile,delimiter=',')
                    newline = j + [dt]
                    outCSV.writerow(newline)

I only become a csv file helloout.csv with one row and that's the last row of file hello.csv with the new column. I think it overwrite the rows but i have no idea why?

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