一周前开始使用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 readFile
openFile.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 readFile
openFile.close()
如果有人能告诉我我在这里做错了还是仅仅是Pythong的事情,我将不胜感激。我正在使用Python 2.7。谢谢!
慕盖茨4494581
相关分类