gpt4 book ai didi

Python文件操作

转载 作者:太空狗 更新时间:2023-10-29 17:17:22 25 4
gpt4 key购买 nike

这个 python 程序出现错误“IOError: [Errno 0] Error”:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
print file.read() # 1
file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

问题是什么?以下这 2 种情况是可以的:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
# print file.read() # 1
file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

和:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
print file.read() # 1
# file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

还是,为什么

print file.tell() # not at the EOF place, why?

不打印文件的大小,“a+”是追加模式吗?那么文件指针应该指向EOF吗?

我正在使用 Windows 7 和 Python 2.7。

最佳答案

Python 使用 stdio 的 fopen 函数并将模式作为参数传递。我假设你使用的是 Windows,因为@Lev 说代码在 Linux 上运行良好。

以下内容来自fopen Windows 的文档,这可能是解决您的问题的线索:

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

因此,解决方案是在 file.write() 调用之前添加 file.seek()。要追加到文件末尾,请使用 file.seek(0, 2)

供您引用,file.seek 的工作方式如下:

To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

[引用:http://docs.python.org/tutorial/inputoutput.html]

正如@lvc 在评论中和@Burkhan 在他的回答中提到的,您可以使用 io module 中更新的 open 函数.但是,我想指出,在这种情况下,写入函数的工作方式并不完全相同——您需要提供 unicode 字符串作为输入 [简单地在您的情况下为字符串添加前缀 a u]:

from io import open
fil = open('text.txt', 'a+')
fil.write('abc') # This fails
fil.write(u'abc') # This works

最后,请避免使用名称“file”作为变量名,因为它指的是内置类型并且会被静默覆盖,从而导致一些难以发现的错误。

关于Python文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11176724/

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