代码之家  ›  专栏  ›  技术社区  ›  OPP

删除文件中包含python中特定变量的行

  •  0
  • OPP  · 技术社区  · 7 年前

    我的测试。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()  
    2 回复  |  直到 7 年前
        1
  •  0
  •   Hai Vu    7 年前

    您需要的是就地编辑,即逐行同时读写。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='' 避免额外的行尾字符。或者,我们可以省略 from __future__ ... 行并使用如下打印语句(注意结尾逗号):

      print line,
      

    使现代化

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

    1. 在以前的代码中,我并没有从 must_delete ,所以看起来 bear\n . 现在我们需要剥离新线路,以便在线路内的任何地方进行测试
    2. 而不是将线条与 必须删除 ,我们必须进行部分字符串比较: 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
    
        2
  •  0
  •   Prune    7 年前
    1. 读取变量 must_delete ,但您可以使用 mustdelete .
    2. 您遍历输出文件(i代表f中的i);我想您需要扫描输入。
    3. 在给定位置截断文件;你确定这就是你想做的吗 在…内 回路?