删除文件中包含 python 中某个变量的行

Removing lines in my file that contain a certain variable in python

我的test.txt长得像

bear
goat
cat

我想做的是获取它的第一行,即 bear 和 find 以及包含它的行然后删除它们,这里的问题是当我 运行 我的代码所做的只是删除我的输出文件的所有内容。

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()  

  1. 您读取了一个变量 must_delete,但您使用 mustdelete 进行解析。
  2. 您遍历输出文件 (i for i in f);我想你想扫描输入。
  3. 您在给定位置截断了文件;您确定这就是您要在 循环中执行的操作吗?

你要的是就地编辑,意思是同时读和写,一行一行。 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
  • 在 with 块中,由于就地编辑,print() 函数(神奇地)将打印到文件,而不是您的控制台。
  • 我们需要用 end='' 调用 print() 以避免额外的行结束字符。或者,我们可以省略 from __future__ ... 行并像这样使用打印语句(注意结尾的逗号):

    print line,
    

更新

如果你想检测第一行的存在(例如'bear')那么还有两件事要做:

  1. 在之前的代码中,我没有从 must_delete 中删除换行符,因此它可能看起来像 bear\n。现在我们需要剥离新行以测试行内的任何地方
  2. 我们必须进行部分字符串比较,而不是将行与 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='')

更新 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