【问题标题】:Python file operationsPython文件操作
【发布时间】:2012-06-24 10:34:27
【问题描述】:

我得到了一个错误“IOError: [Errno 0] Error”这个python程序:

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()

和:

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。

【问题讨论】:

  • 你从哪里得到错误?问题似乎是您正在尝试读取以附加模式打开的文件
  • 另外,你确定 text.txt 存在吗?
  • 您的代码对我来说很好用。 tell 在打开文件后就返回0,当然,你为什么会期待别的呢?
  • 可以添加你使用的Python版本和操作系统吗?
  • 查看我更新的答案,这个修复应该可以工作。我在和你一样的平台+python版本上试过了

标签: python file-io


【解决方案1】:

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

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

当指定了“r+”、“w+”或“a+”访问类型时,都读取 并且允许写入(据说该文件是为“更新”而打开的)。 但是,当你在阅读和写作之间切换时,必须有一个 干预 fflush、fsetpos、fseek 或倒带操作。目前的 可以为 fsetpos 或 fseek 操作指定位置,如果 想要的。

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

供您参考,file.seek 的工作方式如下:

要更改文件对象的位置,请使用 f.seek(offset, from_what)。 位置是通过将偏移量添加到参考点来计算的;这 参考点由 from_what 参数选择。来自什么 值 0 从文件开头测量,1 使用当前 文件位置,2 使用文件的结尾作为参考点。 from_what 可以省略,默认为 0,使用 文件作为参考点。

[参考:http://docs.python.org/tutorial/inputoutput.html]

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

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

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

【讨论】:

  • @LevLevitsky,我无法从文档中确定这一点,但你是对的,代码有效
  • 此外,它打开不存在的文件也没有任何错误。
  • 是的,但是当文件中有一些文本时它会失败
  • 至少在我的系统上没有。
  • 我用的是windows,Python 2.7,你呢?
【解决方案2】:

解决方案是使用open from io

D:\>python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('file.txt','a+')
>>> f.tell()
0L
>>> f.close()
>>> from io import open
>>> f = open('file.txt','a+')
>>> f.tell()
22L

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 2012-02-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多