假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?
当前回答
解决这个问题的方法只有一个:
with open("target.txt", "r+") as f:
d = f.readlines()
f.seek(0)
for i in d:
if i != "line you want to remove...":
f.write(i)
f.truncate()
该解决方案以r/w模式(“r+”)打开文件,并使用seek重置f指针,然后截断以删除最后一次写入之后的所有内容。
其他回答
将文件行保存在一个列表中,然后从列表中删除要删除的行,并将剩余的行写入一个新文件
with open("file_name.txt", "r") as f:
lines = f.readlines()
lines.remove("Line you want to delete\n")
with open("new_file.txt", "w") as new_f:
for line in lines:
new_f.write(line)
这是来自@Lother的答案的一个“分叉”(我相信这应该被认为是正确的答案)。
对于这样的文件:
$ cat file.txt
1: october rust
2: november rain
3: december snow
Lother解决方案中的这个分支工作得很好:
#!/usr/bin/python3.4
with open("file.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "snow" not in line:
f.write(line)
f.truncate()
改进:
使用open,丢弃了f.s close()的用法 更清晰的if/else用于计算当前行中是否存在字符串
我喜欢这个使用fileinput和inplace方法的方法:
import fileinput
for line in fileinput.input(fname, inplace =1):
line = line.strip()
if not 'UnwantedWord' in line:
print(line)
它比其他答案少一点啰嗦而且足够快
如果您使用Linux,可以尝试以下方法。 假设你有一个名为animal.txt的文本文件:
$ cat animal.txt
dog
pig
cat
monkey
elephant
删除第一行:
>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt'])
然后
$ cat animal.txt
pig
cat
monkey
elephant
获取文件的内容,用换行符将其分割成一个元组。然后,访问元组的行号,加入结果元组,并覆盖到文件。