【问题标题】:Removing lines in my file that contain a certain variable in python删除我的文件中包含 python 中某个变量的行
【发布时间】:2018-01-05 01:30:24
【问题描述】:

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

【问题讨论】:

  • i for i in f 是输出文件。应该是线缓存。
  • 你能给我举个例子吗?我对python很陌生
  • @OPP:个别教程超出了 Stack Overflow 的范围。这通常表明您需要的是与当地导师一起半小时或完成教程,而不是 Stack Overflow。

标签: python arrays sorting startswith


【解决方案1】:

您想要的是就地编辑,即逐行同时读取和写入。 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 语句(注意结尾的逗号):

    print line,
    

更新

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

  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

【讨论】:

  • 如果我的输出文件每行有多个内容,然后包含单词“bear”,怎么能想到工作
  • 那么,如果第一行是'bear',你想删除带有'bear cat'、'big bear'、...的行吗?
  • 是的。这正是我正在寻找的
  • 海武是的。这正是我正在寻找的
  • 效果很好!!!!!!不过,还有一件事,我还想计算数据在第二个文件中出现的次数。有没有办法做到这一点?
【解决方案2】:
  1. 您读取了一个变量 must_delete,但您使用 mustdelete 解析。
  2. 您浏览输出文件(i for i in f);我想你想扫描输入。
  3. 您在给定位置截断文件;你确定这就是你想要在循环中做的吗?

【讨论】:

  • 你指的是什么循环?
猜你喜欢
  • 2018-06-15
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多