gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:27:45 26 4
gpt4 key购买 nike

一周前开始使用 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 isentirely undefined unless a file-positioning operation occurs betweenthem (for example, a seek()). I can't guess whatyou expect to happen, but seems most likely that what youintend 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 systemsthat differentiate between binary and text files; on systems thatdon’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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com