将行前置到文件的开头

Ill*_*ist 60 python

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

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

由于文件以追加模式打开,因此从文件末尾开始写入.

eyq*_*uem 92

在模式'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)
Run Code Online (Sandbox Code Playgroud)

第二种方式:

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,
Run Code Online (Sandbox Code Playgroud)

我不知道这种方法是如何工作的,如果它可以在大文件上使用.传递给输入的参数1允许在适当的位置重写一行; 以下行必须向前或向后移动才能进行就地操作,但我不知道机制

  • @TomBrito是的,新的[`with`陈述](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement)允许你避免常见的`try` /`except` /`最终`样板代码.它是在Python版本`2.5`中添加的. (4认同)
  • `with open(filename,'r+') as f:` 会关闭文件吗? (2认同)
  • 第一种方法删除第一行。 (2认同)
  • @SanketDG 最新答案是这样吗?我在第一种方法中没有看到这种行为。 (2认同)

NPE*_*NPE 16

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


jef*_*amp 7

为了将代码放到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)
Run Code Online (Sandbox Code Playgroud)

  • 惨重!用该行将所有文件复制到一个新文件中。 (2认同)
  • @TonyTannous如果您有办法做到这一点,请分享。我知道很多人会感兴趣。 (2认同)

小智 6

不同的想法:

(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)
Run Code Online (Sandbox Code Playgroud)


小智 5

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
Run Code Online (Sandbox Code Playgroud)


Joo*_*ark 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
Run Code Online (Sandbox Code Playgroud)

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

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