可能的重复:
删除文件中的特定行(python)
我需要从文件 f= 中删除包含数字“2”的行
2 3
5 6
7 2
4 5
Run Code Online (Sandbox Code Playgroud)
当您想要编辑文件时,您可以使用正确的数据创建一个新文件,然后将新文件重命名为旧文件。这就是像文本编辑器这样的严肃程序可能会做的事情。(有些文本编辑器实际上做了更奇怪的事情,但这样做是没有用的。)这是因为在许多文件系统中重命名可以是原子的,因此在任何情况下都不会导致原始文件被损坏。
这将导致代码达到以下效果
with open(orig_file) as f, open(working_file, "w") as working:
# ^^^ 2.7+ form, 2.5+ use contextlib.nested
for line in f:
if '2' not in line: # Is this exactly the criterion you want?
# What if a line was "12 5"?
working.write(line)
os.rename(working_file, orig_file)
Run Code Online (Sandbox Code Playgroud)
您可能想使用orig_file + '~'或tempfile模块来生成工作文件。
| 归档时间: |
|
| 查看次数: |
6746 次 |
| 最近记录: |