您需要的是就地编辑,即逐行同时读写。Python具有
fileinput
提供此功能的模块。
from __future__ import print_function
import linecache
import fileinput
must_delete = linecache.getline('Test.txt', 1)
for line in fileinput.input('output.txt', inplace=True):
if line != must_delete:
print(line, end='')
笔记
使现代化
如果要检测第一行(例如“bear”)的存在,那么还有两件事要做:
-
在以前的代码中,我并没有从
must_delete
,所以看起来
bear\n
. 现在我们需要剥离新线路,以便在线路内的任何地方进行测试
-
而不是将线条与
必须删除
,我们必须进行部分字符串比较:
if must_delete in line:
总而言之:
from __future__ import print_function
import linecache
import fileinput
must_delete = linecache.getline('Test.txt', 1)
must_delete = must_delete.strip() # Additional Task 1
for line in fileinput.input('output.txt', inplace=True):
if must_delete not in line: # Additional Task 2
print(line, end='')
更新2
from __future__ import print_function
import linecache
import fileinput
must_delete = linecache.getline('Test.txt', 1)
must_delete = must_delete.strip()
total_count = 0 # Total number of must_delete found in the file
for line in fileinput.input('output.txt', inplace=True):
# How many times must_delete appears in this line
count = line.count(must_delete)
if count > 0:
print(line, end='')
total_count += count # Update the running total
# total_count is now the times must_delete appears in the file
# It is not the number of deleted lines because a line might contains
# must_delete more than once