【问题标题】:How to delete line from the file in python如何在python中从文件中删除行
【发布时间】:2011-09-10 13:48:06
【问题描述】:

我有一个文件 F,内容巨大,例如 F = [1,2,3,4,5,6,7,8,9,...]。所以我想遍历文件 F 并删除文件中包含任何数字的所有行,比如 f = [1,2,4,7,...]。

F = open(file)
f = [1,2,4,7,...]
for line in F:
    if line.contains(any number in f):
        delete the line in F

【问题讨论】:

  • stackoverflow.com/questions/7152250/… 中提供了一个不特定于 python 的好答案。简短的版本是“你不能'只是删除'文件的一部分”
  • 文件是否在不同的行上包含逗号分隔的数字或什么?
  • 1, 2, 3, 4, 5, 6, 7, 8, 9 不是很大的数字
  • 在这种情况下,delete 是什么意思?该文件是索引文件还是只是一个文本文件?

标签: python


【解决方案1】:

您不能立即删除文件中的行,因此必须在其中写入剩余行的位置创建一个新文件。这就是 chonws 示例所做的。

【讨论】:

    【解决方案2】:

    我不清楚您要修改的文件的格式是什么。我假设它看起来像这样:

    1,2,3
    4,5,7,19
    6,2,57
    7,8,9
    128
    

    这样的事情可能对你有用:

    filter = set([2, 9])
    lines = open("data.txt").readlines()
    outlines = []
    for line in lines:
        line_numbers = set(int(num) for num in line.split(","))
        if not filter & line_numbers:
            outlines.append(line)
    if len(outlines) < len(lines):
        open("data.txt", "w").writelines(outlines)
    

    我一直不清楚一次性执行 open() 的含义是什么,但我经常使用它,而且它似乎不会造成任何问题。

    【讨论】:

    • filter 只是一个集合,如何找到其中每一行的数字?
    • @F.C.他取那个和行中数字的交集。
    【解决方案3】:
    exclude = set((2, 4, 8))           # is faster to find items in a set
    out = open('filtered.txt', 'w')
    with open('numbers.txt') as i:     # iterates over the lines of a file
        for l in i:
            if not any((int(x) in exclude for x in l.split(','))):
                out.write(l)
    out.close()
    

    我假设文件只包含用 , 分隔的整数

    【讨论】:

      【解决方案4】:

      像这样?:

      nums = [1, 2]
      f = open("file", "r")
      source = f.read()
      f.close()
      out = open("file", "w")
      for line in source.splitlines():
          found = False
          for n in nums:
              if line.find(str(n)) > -1:
                  found = True
                  break
          if found:
              continue
          out.write(line+"\n")
      out.close()
      

      【讨论】:

      • 你可以让for line in f
      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2020-03-05
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多