在同一个csv文件上读写 [英] read and write on same csv file
问题描述
我正在尝试读取和写入同一个 CSV 文件:
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')
我的 csv 文件是:
My csv files are:
val1,2323,Notes
val2, 2323,Test
所以基本上如果我的 row[2]
值是 Test
我想用 Some new value
替换它.上面的代码给了我空的 CSV 文件.
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.
推荐答案
你应该使用不同的输出文件名.即使您希望名称相同,也应该使用一些临时名称,最后重命名文件.
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.
当您以w"(或wb")模式打开文件时,该文件被清除"——整个文件内容消失.open()
的 Python 文档说:
When you open file in 'w' (or 'wb') mode this file is "cleared" -- whole file content disappears. Python documentation for open()
says:
... 'w' 仅用于写入(已存在的同名文件将被删除),...
所以你的文件在 csv 函数开始解析之前就被删除了.
So your file is erased before csv functions start parsing it.
这篇关于在同一个csv文件上读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!