【问题标题】:How to delete parts of a file in python?如何在python中删除文件的一部分?
【发布时间】:2011-01-14 14:29:00
【问题描述】:

我有一个名为 a.txt 的文件,如下所示:

我是第一行
我是二线。
这里可能会有更多的行。

我在一个空行下面。
我是一条线。
更多行在这里。

现在,我想删除空行上方的内容(包括空行本身)。 我怎么能以 Python 的方式做到这一点?

【问题讨论】:

    标签: python file text-processing


    【解决方案1】:

    基本上你不能从文件开头删除东西,所以你必须写入一个新文件。

    我认为pythonic的方式是这样的:

    # get a iterator over the lines in the file:
    with open("input.txt", 'rt') as lines:
        # while the line is not empty drop it
        for line in lines:
            if not line.strip():
                break
    
        # now lines is at the point after the first paragraph
        # so write out everything from here
        with open("output.txt", 'wt') as out:
            out.writelines(lines)
    

    这里有一些更简单的版本,旧 Python 版本没有with

    lines = open("input.txt", 'rt')
    for line in lines:
        if not line.strip():
            break
    open("output.txt", 'wt').writelines(lines)
    

    还有一个非常直接的版本,它只是在空行处拆分文件:

    # first, read everything from the old file
    text = open("input.txt", 'rt').read()
    
    # split it at the first empty line ("\n\n")
    first, rest = text.split('\n\n',1)
    
    # make a new file and write the rest
    open("output.txt", 'wt').write(rest)
    

    请注意,这可能非常脆弱,例如 Windows 通常使用 \r\n 作为单个换行符,因此空行将改为 \r\n\r\n。但通常你知道文件的格式只使用一种换行符,所以这可能没问题。

    【讨论】:

    • 您可以使用os.linesep 代替'\n',它存储了当前平台的正确行分隔符。
    • @ikostia:这太愚蠢了。您正在处理的文件的换行符可能与您的操作系统默认使用的换行符不同。
    【解决方案2】:

    通过从上到下逐行迭代文件中的行的简单方法:

    #!/usr/bin/env python
    
    with open("4692065.txt", 'r') as src, open("4692065.cut.txt", "w") as dest:
        keep = False
        for line in src:
            if keep: dest.write(line)
            if line.strip() == '': keep = True
    

    【讨论】:

    • 已更正以保持行低于空行。
    【解决方案3】:

    fileinput 模块(来自标准库)对这类事情很方便。它进行了设置,因此您可以像在“就地”编辑文件一样行事:

    import fileinput
    import sys
    
    fileobj=iter(fileinput.input(['a.txt'], inplace=True))
    # iterate through the file until you find an empty line.
    for line in fileobj:
        if not line.strip():
            break
    # Iterators (like `fileobj`) pick up where they left off. 
    # Starting a new for-loop saves you one `if` statement and boolean variable.
    for line in fileobj:
        sys.stdout.write(line)
    

    【讨论】:

      【解决方案4】:

      知道文件有多大吗?

      你可以将文件读入内存:

      f = open('your_file', 'r')
      lines = f.readlines()
      

      它将逐行读取文件并将这些行存储在列表(行)中。

      然后,关闭文件并使用 'w' 重新打开:

      f.close()
      f = open('your_file', 'w')
      for line in lines:
          if your_if_here:
              f.write(line)
      

      这将覆盖当前文件。然后,您可以从列表中选择要写回的行。如果文件变大,可能不是一个好主意,因为整个文件必须驻留在内存中。但是,它不需要您创建第二个文件来转储您的输出。

      【讨论】:

        【解决方案5】:
        from itertools import dropwhile, islice
        
        def content_after_emptyline(file_object):
            return islice(dropwhile(lambda line: line.strip(), file_object), 1, None)
        
        with open("filename") as f:
            for line in content_after_emptyline(f):
                print line,
        

        【讨论】:

          【解决方案6】:

          你可以这样做:

          with open('a.txt', 'r') as file:
              lines = file.readlines()
          
          blank_line = lines.index('\n')
          lines = lines[blank_line+1:] #\n is the index of the blank line
          
          with open('a.txt', 'w') as file:
              file.write('\n'.join(lines))
          

          这让工作变得更加简单。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-09-16
            • 2010-11-06
            相关资源
            最近更新 更多