相关疑难解决方法(0)

初学者Python:读取和写入同一个文件

一周前开始使用Python,我有一些关于阅读和写入相同文件的问题.我已经在线阅读了一些教程,但我仍然对此感到困惑.我可以理解简单的读写文件.

openFile = open("filepath", "r")
readFile = openFile.read()
print readFile 

openFile = open("filepath", "a")
appendFile = openFile.write("\nTest 123")

openFile.close()
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试以下操作,我会在写入的文本文件中收到一堆未知文本.任何人都可以解释为什么我会收到这样的错误,为什么我不能使用相同的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()
Run Code Online (Sandbox Code Playgroud)

我会尽力澄清我的问题.在上面的示例中,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()
Run Code Online (Sandbox Code Playgroud)

如果有人能告诉我这里做错了什么,或者只是一个Pythong的事情,我将不胜感激.我使用的是Python 2.7.谢谢!

python io

24
推荐指数
2
解决办法
7万
查看次数

标签 统计

io ×1

python ×1