读和写在同一csv文件 [英] read and write on same csv file

查看:242
本文介绍了读和写在同一csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一个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文件是:


  • val1,2323,Notest

  • val2,2323,Test li>
  • val1,2323,Notest
  • val2, 2323,Test

所以基本上如果我的 row [2] value是 Test 我想用一些新值替换它。
上面的代码给出了空的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' )模式下,此文件被清除 - 整个文件内容消失。 Python文档 open()说:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆