我有一个代码,应该写一个文本文件,然后用一些其他东西替换一行中的一些文本.
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')
Run Code Online (Sandbox Code Playgroud)
一开始没关系.它读取第一行并设置指向文件开头的指针.但是当它应该读取一行并将指针放在第二行时,它将它放在文件的末尾.如果我将它分配给变量,它只读取一行,但它仍然将指针设置在文件的末尾.
显然readline()不能像我想象的那样工作,所以请告诉我如何阅读文本的某些行并将内容写入特定行.