Possible Duplicate:
Deleting a specific line in a file (python)如何從文件中的蟒蛇刪除線
我需要刪除的行包含從文件f數「2」 =
2 3
5 6
7 2
4 5
Possible Duplicate:
Deleting a specific line in a file (python)如何從文件中的蟒蛇刪除線
我需要刪除的行包含從文件f數「2」 =
2 3
5 6
7 2
4 5
with open('f', 'r+') as f:
data = ''.join(filter(lambda l: '2' not in l.strip().split(' '), f))
f.seek(0)
f.truncate(0)
f.write(data)
當你想編輯一個文件,請使用正確的數據創建新的文件,然後將新文件重命名爲舊文件。這就是你的文本編輯器可能做的嚴肅的程序。 (有些文本編輯器實際上甚至做的更加怪異,但沒有用處。)這是因爲在許多文件系統中,重命名可以是原子,這樣在任何情況下最終都不會損壞原始文件。
這將導致代碼,您可能需要使用orig_file + '~'
的
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)
效果或產生的工作文件tempfile
模塊。
import fileinput
for line in fileinput.input('f',inplace =1):
line = line.strip()
if not '2' in line:
print line
無論如何,這是作業嗎? –