一周前开始使用Python,我有一些关于读写相同文件的问题。我已经在线阅读了一些教程,但对此仍然感到困惑。我可以理解简单的读写文件。openFile = open("filepath", "r")readFile = openFile.read()print readFile openFile = open("filepath", "a")appendFile = openFile.write("\nTest 123")openFile.close()但是,如果我尝试以下操作,则会在要写入的文本文件中得到一堆未知文本。谁能解释我为什么会收到这样的错误,以及为什么我不能以如下所示的方式使用相同的openFile对象。# I get an error when I use the codes below: openFile = open("filepath", "r+")writeFile = openFile.write("Test abc")readFile = openFile.read()print readFileopenFile.close()我将尝试澄清我的问题。在上面的示例中,openFile是用于打开文件的对象。如果我想第一次写它,我没有问题。如果我想使用相同的openFile来读取文件或向其附加内容。它不会发生或给出错误。我必须声明相同/不同的打开文件对象,然后才能对同一文件执行另一个读/写操作。#I have no problems if I do this: openFile = open("filepath", "r+")writeFile = openFile.write("Test abc")openFile2 = open("filepath", "r+")readFile = openFile2.read()print readFileopenFile.close()如果有人能告诉我我在这里做错了还是仅仅是Pythong的事情,我将不胜感激。我正在使用Python 2.7。谢谢!
3 回答

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
读和写发生在当前文件指针所在的位置,并且每次读/写都会前进。在您的特定情况下,写入openFile
会导致文件指针指向文件末尾。尝试从末尾读取将导致EOF。您需要重置文件指针,以使其指向文件的开头,然后seek(0)
再进行读取。
添加回答
举报
0/150
提交
取消