Skip to main content
 首页 » 编程设计

python之为什么 readline() 在 Python 中将文件指针放在文件末尾

2025年05月04日30soundcode

我有一个代码,应该编写一个文本文件,然后用其他内容替换一行中的一些文本。

def read(text): 
 
    file = open('File.txt', 'r+') #open the file for reading and writing  
    x = file.readline() # read the first line of the file   
    file.seek(0, 0) #put the pointer back to the begining 
    file.readline() #skip one line 
    file.write(text) #write the text 
    file.close() #close the file 
 
read('ABC') 

一开始还好。它读取第一行并将指针设置为文件的开头。但是当它应该读取一行并将指针放在第二行时,它会将它放在文件的末尾。如果我将其分配给一个变量,它只会读取一行,但它仍会将指针设置在文件末尾。

显然 readline() 没有像我想的那样工作,所以请告诉我如何读取文本的某些行并向特定行写入内容。

请您参考如下方法:

默认情况下,写入始终发生在文件末尾。调用 file.readline() 不会改变此行为,特别是因为 readline() 调用可以使用缓冲区来读取更大的 block 。

您可以通过使用 file.seek() 明确地转到一行的末尾来覆盖;你只读了这行,你知道长度,寻找到那一点:

x = file.readline() 
file.seek(len(x), 0) 
file.write(text) #write the text 

请注意,您不能插入行,也不能轻易替换行。文件是单个字节流,而不是行,因此如果您在一行中写入 10 个字符(包括换行符),则只能用其他 10 个字符替换该行。更长或更短的线路在这里不起作用;您只需替换文件中更少或更多的字符,并部分替换一行或覆盖(部分)下一行。