在文件开头加上一行


76

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

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

由于文件是在追加模式下打开的,因此此操作从文件末尾开始写入。



1
不,这不是解决方案,因为该链接不能用于附加文件,它将保留在最后一行。
Rikudo Pain

Answers:


109

在模式'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,

我不知道这种方法如何在后台运行,以及是否可以在大文件中使用。传递给输入的参数1允许在适当位置重写一行;为了进行就地操作,必须向前或向后移动以下几行,但是我不知道该机制


2
with open(filename,'r+') as f:将关闭文件?
汤姆·布里托

6
@TomBrito是的,新with的语句可以让你避免常见的try/ except/finally样板代码。它是在Python版本中添加的2.5
杰西·韦伯

2
第一种方法删除第一行。
SanketDG

@SanketDG最新答案是否正确?我看不到第一种方法的行为。
戴夫C,

16

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


13

为了使代码成为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)

2
惨重!用该行将所有文件复制到一个新文件中。
Tony Tannous

11
@TonyTannous如果您有办法做到这一点,请分享。我知道很多人会感兴趣。
jeffpkamp

8

不同的想法:

(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)

3

无法使用任何内置函数来执行此操作,因为这样做效率极低。每次在前面添加一行时,都需要向下移动文件的现有内容。

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


3
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

3

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

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

请注意,这不是就地替换。它正在再次写入文件。

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


1
with open("fruits.txt", "r+") as file:
    file.write("bab111y")
    file.seek(0)
    content = file.read()
    print(content)

0

如果文件太大而不能用作列表,而您只想反转文件,则可以首先以相反的顺序写入文件,然后一次从文件末尾读取一行(然后将其写入另一个文件) )和文件读取后退模块

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.