【问题标题】:File Reading problems in PythonPython中的文件读取问题
【发布时间】:2013-06-05 02:40:58
【问题描述】:

在使用 python 读取文件时 f = open ("filename.txt") 并使用 f.read(1) 最后找到流usibg的位置 f.tell() 每一步;我们得到一个从 0 到当前位置的连续编号。

我面临的问题是,对于某些职位,我实际上得到了一个随机数作为f.tell(),然后继续这些数字。 例如,f.tell() 输出类似于以下内容

0
1
2
3
133454568679978
6
7
8...

知道为什么会这样吗?

我的代码:

f=open("temp_mcompress.cpp")
current = ' '
   while current != '' :
   print(f.tell())
   current = f.read(1)

f.close()

Temp_mcompress.cpp 文件:

#include <iostream>

int main(int a)
{
}

输出: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551636 18446744073709551638 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 18446744073709551655 40 41 43 44

【问题讨论】:

  • 您的代码对我有用。我得到 0 ... 41。你想做什么?您可以使用以下方法获得相同的结果: import os for pos in range(0, os.path.getsize("temp_mcompress.cpp") + 1): print pos
  • 我实际上是在阅读文件和操作,但我经常面临这个错误。我不明白为什么我的输出如此随机出现问题。

标签: string file-io python-3.x


【解决方案1】:

看来我可能发现了仍然适用于 python 3.x 的问题: 来源:http://docs.python.org/2.4/lib/bltin-file-objects.html

告诉()

返回文件的当前位置,如 stdio 的 ftell()。

注意:在 Windows 上,tell() 可以返回非法值(在 fgets() 之后) 读取带有 Unix 风格行尾的文件时。使用二进制模式 ('rb') 来规避这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2019-12-22
    相关资源
    最近更新 更多