为什么读操作在此代码中不起作用?

时间:2020-04-24 12:56:35

标签: python

我正在学习python文件操作,并且正在尝试不同的读取和写入选项。 据我所知,这段代码应该能够添加和读取test.txt文件,因为我已经用“ a +”打开了它。但是,尽管append操作按预期运行,但我没有从print函数获得任何输出。

my_file = open('test.txt', 'a+') 
my_file.write("You know nothin' Jon Snow.") 
content = my_file.read() 
print(content)
my_file.close()

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

首次打开文件时,文件指针位于文件末尾。写操作使文件指针紧随新文本之后。当您尝试阅读时,没有 left 可供阅读;您已经在文件末尾了。如果您想读取文件的全部内容,则需要先查找开头,然后再读取。

with open('test.txt', 'a+') as my_file:
    my_file.write("You know nothin' Jon Snow.") 
    my_file.seek(0)
    content = my_file.read() 
    print(content)

答案 1 :(得分:2)

由于执行写操作后,现在位于文件的末尾,因此执行读操作时,没有要读取的内容。您需要先执行seek才能将自己放置在文件结尾之前的某个位置:

my_file = open('test.txt', 'a+')
my_file.write("You know nothin' Jon Snow.")
my_file.seek(0)
content = my_file.read()
print(content)
my_file.close()