小编Rok*_*can的帖子

为什么readline()将文件指针放在Python的文件末尾?

我有一个代码,应该写一个文本文件,然后用一些其他东西替换一行中的一些文本.

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()不能像我想象的那样工作,所以请告诉我如何阅读文本的某些行并将内容写入特定行.

python pointers file

1
推荐指数
1
解决办法
146
查看次数

标签 统计

file ×1

pointers ×1

python ×1