Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - read and write on same csv file

I am trying to read and write on the same CSV file:

file1 = open(file.csv, 'rb')
file2 = open(file.csv, 'wb')
reader = csv.reader(file1)
writer = csv.writer(file2)
for row in reader:
   if row[2] == 'Test':
      writer.writerow( row[0], row[1], 'Somevalue')

My csv files are:

  • val1,2323,Notest
  • val2, 2323,Test

So basically if my row[2] value is Test I want to replace it with Some new value. The above code gives me empty CSV files.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use different output file name. Even if you want the name to be the same, you should use some temporary name and finally rename file.

When you open file in 'w' (or 'wb') mode this file is "cleared" -- whole file content disappears. Python documentation for open() says:

... 'w' for only writing (an existing file with the same name will be erased), ...

So your file is erased before csv functions start parsing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...