简体   繁体   中英

Python 3 - How to write specific row in same file csv?

I want to update a fieldname called "done" in same file csv

This is structure of file csv:

Input:

Email            Done
 1@gmail.com       
 2@gmail.com       
 3@gmail.com
 4@gmail.com

Output:

Email            Done
 1@gmail.com       1
 2@gmail.com       1
 3@gmail.com       1
 4@gmail.com       1

What I want look like:

import csv
with open(r'E:\test.csv','r', encoding='utf-8') as f:
    reader = csv.DictReader(f,delimiter='|')

    for row in reader:
      #do something here#
      #then write "1" to filename "done"
f.close()

How to do it ? Thank you very much ! :)

With a simple change like this you could use a simple pair of read and write files; read a line, and write it back out immediately with the addition.

In [6]: with open('test.csv','r') as input:
   ...:    with open('test1.csv','w') as output:
   ...:        header=input.readline()
   ...:        output.write(header)
   ...:        for line in input:
   ...:            output.write('%s %8d\n'%(line.strip(),1))

In [7]: cat test1.csv
Email            Done
1@gmail.com        1
2@gmail.com        1
3@gmail.com        1
4@gmail.com        1

You could also use a csv reader and csv writer; A numpy user might be tempted to use the loadtxt and savetxt pair, though mixing string and number values in an array takes a bit more know-how.

In a new enough Python you could put both opens in one with context:

with open('test.csv','r') as input, open('test1.csv','w') as output:
    ...

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