Python 文件操作

2024-03-18

我用这个 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()

and:

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 https://msdn.microsoft.com/en-us/library/yeby3zcb.aspxWindows 文档,这可能是解决您的问题的线索:

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

所以,解决方案是添加file.seek()之前file.write()称呼。要附加到文件末尾,请使用file.seek(0, 2).

供您参考,file.seek 的工作原理如下:

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

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

正如 @lvc 在评论中和 @Burkhan 在他的回答中提到的,您可以使用来自IO模块 http://docs.python.org/library/io.html。但是,我想指出的是,在这种情况下 write 函数的工作方式并不完全相同——您需要提供 unicode 字符串作为输入 [只需在前面加上 au到你的情况下的字符串]:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 文件操作 的相关文章

  • Twisted 的 Deferred 和 JavaScript 中的 Promise 一样吗?

    我开始在一个需要异步编程的项目中使用 Twisted 并且文档非常好 所以我的问题是 Twisted 中的 Deferred 与 Javascript 中的 Promise 相同吗 如果不是 有什么区别 你的问题的答案是Yes and No
  • 使用 pygame 显示 unicode 符号

    我检查了其他答案 但不明白为什么我的代码错误地显示 This is what I currently see https i stack imgur com 8tNIK png 这是关于文本渲染的相关代码 font pygame font
  • 如何以“正确”的方式处理带有空字节的 Python unicode 字符串?

    Question PyWin32 似乎很乐意将 null 终止的 unicode 字符串作为返回值 我想以 正确 的方式处理这些字符串 假设我得到一个像这样的字符串 u C Users Guest MyFile asy x00 x00sy
  • 检查 Python 中的可迭代对象中的所有元素的谓词是否计算为 true

    我很确定有一个常见的习语 但我无法通过谷歌搜索找到它 这是我想做的 用Java Applies the predicate to all elements of the iterable and returns true if all ev
  • sklearn 中的 pca.inverse_transform

    将我的数据拟合后 X 我的数据 pca PCA n components 1 pca fit X X pca pca fit transform X 现在 X pca 具有一维 当我根据定义执行逆变换时 它不是应该返回原始数据 即 X 二维
  • Keras:如何保存模型或权重?

    如果这个问题看起来很简单 我很抱歉 但是阅读 Keras 保存和恢复帮助页面 https www tensorflow org beta tutorials keras save and restore models https www t
  • Python新式类和__subclasses__函数

    有人可以向我解释为什么这有效 在 Python 2 5 中 class Foo object pass class Bar Foo pass print Foo subclasses 但这不是 class Foo pass class Ba
  • .pyx 文件出现未知文件类型错误

    我正在尝试构建一个包含 pyx 文件的 Python 包 pyregion 但在构建过程中出现错误 检查以下输出 python setup py build running build running build py creating b
  • 时间:2019-03-17 标签:c++fstream并发访问

    如果从不同的进程 线程同时访问文件会发生什么 据我所知 没有锁定文件的标准方法 只有操作系统特定的功能 就我而言 文件将被经常读取而很少写入 现在如果A打开一个文件进行读取 ifstream 并开始读取块 和B打开相同的文件进行写入 ofs
  • 如何在 pandas 中使用 read_fwf 跳过空行?

    I use pandas read fwf http pandas pydata org pandas docs stable generated pandas read fwf htmlPython pandas 0 19 2 中的函数读
  • 使用 Pandas 计算 delta 列

    我有一个数据框 如下所示 Name Variable Field A 2 3 412 A 2 9 861 A 3 5 1703 B 3 5 1731 A 4 0 2609 B 4 0 2539 A 4 6 2821 B 4 6 2779 A
  • 使用 Keras np_utils.to_categorical 的问题

    我正在尝试将整数的 one hot 向量数组制作为 keras 将能够使用的 one hot 向量数组来拟合我的模型 这是代码的相关部分 Y train np hstack np asarray dataframe output vecto
  • 返回表示每组内最大值的索引的一系列数字位置

    考虑一下这个系列 np random seed 3 1415 s pd Series np random rand 100 pd MultiIndex from product list ABDCE list abcde One Two T
  • 动态过滤 pandas 数据框

    我正在尝试使用三列的阈值来过滤 pandas 数据框 import pandas as pd df pd DataFrame A 6 2 10 5 3 B 2 5 3 2 6 C 5 2 1 8 2 df df loc df A gt 0
  • Elasticsearch 通过搜索返回拼音标记

    我用语音分析插件 https www elastic co guide en elasticsearch plugins current analysis phonetic html由于语音转换 从弹性搜索中进行一些字符串匹配 我的问题是
  • 如何与其他用户一起使用 pyenv?

    如何与其他用户一起使用 pyenv 例如 如果我在用户 test 的环境中安装了 pyenv 则当我以 test 身份登录时可以使用 pyenv 但是 当我以其他用户 例如 root 身份登录时如何使用 pyenv 即使你这么做了 我也会s
  • Django 与谷歌图表

    我试图让谷歌图表显示在我的页面上 但我不知道如何将值从 django 视图传递到 javascript 以便我可以绘制图表 姜戈代码 array Year Sales Expenses 2004 1000 400 2005 1170 460
  • 双击打开 ipython 笔记本

    相关文章 通过双击 osx 打开 ipython 笔记本 https stackoverflow com questions 16158893 open an ipython notebook via double click on osx
  • 从 pandas DataFrame 中删除少于 K 个连续 NaN

    我正在处理时间序列数据 我在从数据帧列中删除小于或等于阈值的连续 NaN 时遇到问题 我尝试查看一些链接 例如 标识连续 NaN 出现的位置以及计数 Pandas NaN 孔的游程长度 https stackoverflow com que
  • 使用ssl和socket的python客户端身份验证

    我有一个 python 服务器 需要客户端使用证书进行身份验证 我如何制作一个客户端脚本 使用客户端证书由 python 中的服务器使用 ssl 和套接字模块进行身份验证 有没有仅使用套接字和 ssl 而不扭曲的示例 from OpenSS

随机推荐