在文件开头添加一行 [英] Prepend line to beginning of a file

查看:43
本文介绍了在文件开头添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can do this using a separate file, but how do I append a line to the beginning of a file?

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

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

This starts writing from the end of the file since the file is opened in append mode.

推荐答案

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

In modes 'a' or 'a+', any writing is done at the end of the file, even if at the current moment when the write() function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.

第一种方式,可以在将文件加载到内存中没有问题的情况下使用:

1st way, can be used if there are no issues to load the file into memory:

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 允许重写一行;以下几行必须向前或向后移动才能进行就地操作,但我不知道机制

I don't know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don't know the mechanism

这篇关于在文件开头添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆