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

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

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

我在这里做错了什么?

评论
  • lsunt
    lsunt 回复

    Because after you do the write you are now positioned at the end of the file so when you do a read operation there is nothing to read. You need to do first do a seek to position yourself somewhere before the end of file:

    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()
    
  • bdicta
    bdicta 回复

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

    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)