python - 初学者 Python : Reading and writing to the same file

标签 python io

一周前开始使用 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。谢谢!

最佳答案

更新回复:

这似乎是 Windows 特有的错误 - http://bugs.python.org/issue1521491 .

引用 http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html 中解释的解决方法

the effect of mixing reads with writes on a file open for update is entirely undefined unless a file-positioning operation occurs between them (for example, a seek()). I can't guess what you expect to happen, but seems most likely that what you intend could be obtained reliably by inserting

fp.seek(fp.tell())

在 read() 和你的 write() 之间。

我的原始回复演示了如何读取/写入为附加而打开的同一文件。如果您使用的是 Windows,这显然是不正确的。

原始回复:

在 'r+' 模式下,使用 write 方法将根据指针的位置将字符串对象写入文件。在您的情况下,它将字符串“Test abc”附加到文件的开头。请参阅下面的示例:

>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\n'
>>> f.write("foooooooooooooo")
>>> f.close()
>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\nfoooooooooooooo'

字符串“foooooooooooooo”被附加到文件末尾,因为指针已经在文件末尾。

您是否使用区分二进制文件和文本文件的系统?在这种情况下,您可能希望使用 'rb+' 作为模式。

Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect. http://docs.python.org/2/library/functions.html#open

关于python - 初学者 Python : Reading and writing to the same file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14271216/

相关文章:

java - 在同一文件中存储纯文本和字节信息 - 转换问题

python - 根据不同列上的多个条件创建列

python - PyTesser 简单使用错误

python - 重写 python 函数而不使用检查模块

python - 包含函数的序列的递归公式

java - 当我尝试写入文件时,为什么 Eclipse IDE 会给出终止错误?

android - 如何读取android上特定目录中的文件和文件夹

python - 更新解析用户信息以跟踪 kivy 应用程序中的玩家分数

java - 字符串无法转换为数组

c++ - 从 .txt 中读取带有空格的整行文本到单个变量 C++