我的test.txt看起来像
bear
goat
cat
我想要做的是拿它的第一行,这是熊和查找和包含它的行然后删除它们,这里的问题是当我运行我的代码它所做的一切都是删除我的所有内容输出文件。
import linecache
must_delete = linecache.getline('Test.txt', 1)
with open('output.txt','r+') as f:
data = ''.join([i for i in f if not i.lower().startswith(must_delete)])
f.seek(0)
f.write(data)
f.truncate()
答案 0 :(得分:0)
must_delete
,但是使用mustdelete
解析。答案 1 :(得分:0)
你想要的就是就地编辑,意思是一行一行地同时读写。 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='')
fileinput.input()
的调用包含指定就地编辑的参数inplace=True
print()
功能(通过魔术)将打印到文件,而不是您的控制台。我们需要使用print()
调用end=''
以避免额外的行结束字符。或者,我们可以省略from __future__ ...
行并使用这样的print语句(注意结束逗号):
print line,
如果你想检测第一行的存在(例如'熊')那么还有两件事要做:
must_delete
中删除新行,因此它可能看起来像bear\n
。现在我们需要剥离新行,以便在行内的任何地方进行测试must_delete
进行比较: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='')
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