[英]How to delete or replace specific line of csv file
我只想通过使用 os 和 sys 模块(版本为 python 3)来删除和替换 CSV 文件上的函数。
我试过这个替换功能:
file = "test.csv"
keyword = "blah"
old = "the old word"
new = "the new word"
with open(file, "r") as f:
lines = f.readlines()
with open(file, "w") as f:
for line in lines:
if keyword in line:
line.replace(old, new)
这用于删除功能:
file = "test.csv"
keyword = "blahblah"
with open(file, "r") as f:
lines = f.readlines()
with open(file, "w") as f:
for line in lines:
if line.strip("\n") != keyword:
f.write(line)
字符串是不可变的。
.replace()
并期望变量改变replace()
方法调用不会更新磁盘上的文件; 例如你需要调用f.write(line.replace(...))
open(file, 'w')
正在清除文件内容。 因此,您的替换代码会留下一个空文件。
假设您的行与您的关键字完全匹配,您的删除代码似乎没问题,因为它是这篇文章的副本,但是如果您多次运行它,那么您会不断修改同一个文件,因此下次运行时不会发生任何事情因为所有关键字都将消失。
如果您想根据 CSV 的列删除,那么您应该在 CSV if keyword not in line.split(',')
上拆分该行,并使用类似if keyword not in line.split(',')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.