修改文件中的一行

Fox*_*son 5 python file-io for-loop

有没有办法在 Python 中修改文件中的单行,而无需 for 循环遍历所有行?

文件中需要修改的确切位置是未知的。

sen*_*rle 5

除非我们讨论的是一种相当人为的情况,即您已经对该文件了解很多,否则答案是否定的。您必须迭代文件以确定换行符在哪里;当涉及到文件存储时,“行”没有什么特别之处——看起来都是一样的。


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

但是,如果文件大小太大,这可能会消耗资源(时间和内存),因为该f.readlines()函数会加载整个文件,并在列表中分成行。
这对于中小型文件来说就很好了。

  • 这是正确的,因为这通常是正确的方法;然而,它并没有回答OP的实际问题,因为“readlines”会迭代文件中的所有行。 (2认同)