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

问题描述 投票:0回答:2

我的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()  
python arrays sorting startswith
2个回答
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='')

Notes

  • fileinput.input()的调用包括参数inplace=True,它指定了就地编辑
  • 在with块中,由于就地编辑,print()函数(通过魔术)将打印到文件,而不是您的控制台。
  • 我们需要用print()调用end=''以避免额外的行结束字符。或者,我们可以省略from __future__ ...行并使用这样的print语句(注意结束逗号): print line,

Update

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

  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='')

Update 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

0
投票
  1. 你读了一个变量must_delete,但你用mustdelete解析。
  2. 你遍历输出文件(我在f中为i);我想你想要扫描输入。
  3. 您在给定位置截断文件;你确定你想在循环中做什么吗?
© www.soinside.com 2019 - 2024. All rights reserved.