在Python中修改文件的第一行

33 投票
7 回答
30093 浏览
提问于 2025-04-17 16:18

我只需要读取一个大文件的第一行并对其进行修改。

有没有什么简单的方法可以只修改文件的第一行,然后把它保存为另一个文件,使用Python来实现?我所有的代码都是用Python写的,这样可以保持一致性。

我的想法是,不想读取整个文件再写回去。

7 个回答

4

这是一个替代方案,不需要逐行检查那些不感兴趣的内容。

def replace_first_line( src_filename, target_filename, replacement_line):
    f = open(src_filename)
    first_line, remainder = f.readline(), f.read()
    t = open(target_filename,"w")
    t.write(replacement_line + "\n")
    t.write(remainder)
    t.close()
5

如果你想修改一个文件的第一行,并把它保存为一个新文件名,不能只改第一行而不查看整个文件。好消息是,只要你不是把内容打印到终端,修改文件的第一行是非常非常快的,即使文件很大也没问题。

假设你处理的是文本文件(不是二进制文件),这样做应该能满足你的需求,并且在大多数应用中表现得很好。

import os
newline = os.linesep # Defines the newline based on your OS.

source_fp = open('source-filename', 'r')
target_fp = open('target-filename', 'w')
first_row = True
for row in source_fp:
    if first_row:
        row = 'the first row now says this.'
        first_row = False
    target_fp.write(row + newline)
38

shutil.copyfileobj() 这个函数比逐行复制文件要快很多。文档中提到:

注意,如果 [from_file] 对象的当前文件位置不是 0,那么只会复制从当前文件位置到文件末尾的内容。

因此:

from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

撰写回答