修改文件中的一行

7 投票
3 回答
10599 浏览
提问于 2025-04-16 20:10

在Python中,有没有办法可以不通过一个个循环所有行的方式,直接修改文件中的某一行呢?

而且,文件中需要修改的具体位置是未知的。

3 个回答

3

是的,你可以直接修改文件中的某一行,但如果这行的长度发生变化,你就需要重新写入文件中后面的内容。

你还需要知道这行在文件中的位置。这通常意味着程序需要至少读取到需要更改的那一行。

不过也有例外情况,比如如果所有的行都是固定长度,或者你在文件中有某种索引的话。

5

除非我们讨论的是一种非常特殊的情况,比如你已经对这个文件了解很多,否则答案是否定的。你需要逐行读取文件,才能找出换行符的位置;在文件存储中,“行”并没有什么特别之处——所有内容看起来都是一样的。

5

这个方法应该是可行的 -

f = open(r'full_path_to_your_file', 'r')    # pass an appropriate path of the required file
lines = f.readlines()
lines[n-1] = "your new text for this line"    # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
f.close()   # close the file and reopen in write mode to enable writing to file; you can also open in append mode and use "seek", but you will have some unwanted old data if the new data is shorter in length.

f = open(r'full_path_to_your_file', 'w')
f.writelines(lines)
# do the remaining operations on the file
f.close()

不过,如果你的文件太大,这样做可能会消耗很多资源(包括时间和内存),因为 f.readlines() 这个函数会把整个文件都加载进来,并且按行分割成一个列表。
对于小文件和中等大小的文件,这样做是没问题的。

撰写回答