【问题标题】:Prepend line to beginning of a file将行添加到文件的开头
【发布时间】:2011-05-06 16:56:31
【问题描述】:

我可以使用单独的文件来执行此操作,但是如何在文件开头附加一行?

f=open('log.txt','a')
f.seek(0) #get to the first position
f.write("text")
f.close()

这是从文件末尾开始写入的,因为文件是以追加模式打开的。

【问题讨论】:

标签: python


【解决方案1】:

'a''a+' 模式下,任何写入都在文件末尾完成,即使在触发write() 函数的当前时刻,文件的指针不在文件末尾:指针在任何写入之前移动到文件末尾。你可以通过两种方式做你想做的事。

第一种方式,如果将文件加载到内存中没有问题,可以使用:

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

第二种方式

def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print line_to_prepend.rstrip('\r\n') + '\n' + xline,
        else:
            print xline,

我不知道这种方法在后台是如何工作的,以及它是否可以用于大文件。传递给 input 的参数 1 允许就地重写一行;以下行必须向前或向后移动才能进行就地操作,但我不知道机制

【讨论】:

  • with open(filename,'r+') as f: 会关闭文件吗?
  • @TomBrito 是的,新的with statement 允许您避免常见的try/except/finally 样板代码。它是在 Python 版本 2.5 中添加的。
  • 第一种方式删除第一行。
  • @SanketDG 最新答案是这样吗?第一种方法我看不到这种行为。
【解决方案2】:

在我熟悉的所有文件系统中,您无法就地执行此操作。您必须使用辅助文件(然后您可以将其重命名为原始文件的名称)。

【讨论】:

    【解决方案3】:

    要将代码放入 NPE 的答案中,我认为最有效的方法是:

    def insert(originalfile,string):
        with open(originalfile,'r') as f:
            with open('newfile.txt','w') as f2: 
                f2.write(string)
                f2.write(f.read())
        os.rename('newfile.txt',originalfile)
    

    【讨论】:

    • 灾难性的!使用该行将所有文件复制到一个新文件中。
    • @TonyTannous 如果你有办法做到这一点,请分享。我知道很多人都会感兴趣。
    【解决方案4】:

    不同的想法:

    (1) 将原始文件保存为变量。

    (2) 用新信息覆盖原始文件。

    (3) 你将原始文件追加到新信息下方的数据中。

    代码:

    with open(<filename>,'r') as contents:
          save = contents.read()
    with open(<filename>,'w') as contents:
          contents.write(< New Information >)
    with open(<filename>,'a') as contents:
          contents.write(save)
    

    【讨论】:

    • ^^^ 这是黄金^^^
    • a模式下不需要第二次打开文件,你可以在同一个with open块中做两个writes。
    【解决方案5】:

    如果您不介意再次写入文件,则执行此操作的明确方法如下

    with open("a.txt", 'r+') as fp:
        lines = fp.readlines()     # lines is list of line, each element '...\n'
        lines.insert(0, one_line)  # you can use any index if you know the line index
        fp.seek(0)                 # file pointer locates at the beginning to write the whole file again
        fp.writelines(lines)       # write whole lists again to the same file
    

    请注意,这不是就地替换。又在写文件了。

    总而言之,您读取文件并将其保存到列表中,然后修改列表并将列表再次写入具有相同文件名的新文件。

    【讨论】:

      【解决方案6】:

      使用任何内置函数都无法做到这一点,因为它的效率非常低。每次在前面添加一行时,都需要将文件的现有内容向下移动。

      有一个 Unix/Linux 实用程序 tail 可以从文件末尾读取。也许您会发现它在您的应用程序中很有用。

      【讨论】:

        【解决方案7】:
        num = [1, 2, 3] #List containing Integers
        
        with open("ex3.txt", 'r+') as file:
            readcontent = file.read()  # store the read value of exe.txt into 
                                        # readcontent 
            file.seek(0, 0) #Takes the cursor to top line
            for i in num:         # writing content of list One by One.
                file.write(str(i) + "\n") #convert int to str since write() deals 
                                           # with str
            file.write(readcontent) #after content of string are written, I return 
                                     #back content that were in the file
        

        【讨论】:

          【解决方案8】:
          with open("fruits.txt", "r+") as file:
              file.write("bab111y")
              file.seek(0)
              content = file.read()
              print(content)
          

          【讨论】:

          • 这是不正确的。文件的前 7 个字符将替换为“bab111y”,而不是附加到文件的开头。
          【解决方案9】:

          如果文件太大而无法用作列表,而您只是想反转文件,您可以先以相反的顺序写入文件,然后从文件末尾读取一行(并写入到另一个文件)带有文件读取向后模块

          【讨论】:

            【解决方案10】:

            对@eyquem 提供的现有解决方案的改进如下:

            def prepend_text(filename: Union[str, Path], text: str):
                with fileinput.input(filename, inplace=True) as file:
                    for line in file:
                        if file.isfirstline():
                            print(text)
                        print(line, end="")
            

            它是有类型的、整洁的、更具可读性的,并且使用了近年来 python 的一些改进,比如上下文管理器 :)

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-03-20
              • 2019-10-06
              • 2012-01-02
              • 2017-09-09
              • 1970-01-01
              • 2018-02-05
              相关资源
              最近更新 更多