gpt4 book ai didi

python - Python 的 tell() 在 Mac OS X 10.8 和 Ubuntu 10.04 上表现不同

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:24 24 4
gpt4 key购买 nike

我正在处理一个二进制文件(.gz 文件),试图以追加模式 (ab+) 打开它。

正如文件 open() 所保证的那样,以附加模式打开它会导致 tell() 指向文件末尾 (EOF)。但这不是我在 Ubuntu 10.04 上看到的,因为以追加模式打开文件时文件指针仍然指向文件的开头而不是结尾。但在我的 Mac OS X 10.8 上情况并非如此,因为函数按预期正常运行

Ubuntu 10.04 上的行为

Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fp = open("file_name.gz", "ab+")
>>> fp.tell()
0

虽然搜索给了我正确的数字

>>> fp.seek(0, 2)
>>> fp.tell()
753236

Mac OS X 10.8 上的行为

Python 2.6.7 (r267:88850, Oct 11 2012, 20:15:00) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> fp = open("file_name.gz", "ab+")
>>> fp.tell()
753236

在其他模式“a”和“a+b”中观察到相同的行为。有没有人遇到过这样的情况?

最佳答案

作为the documentation说:

'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position)

与文件指针的起始位置无关,甚至括号内的部分也仅在“某些 Unix 系统”上为真。但是您希望它在所有平台上都以相同的方式工作。不要那样做。

正确的答案是明确地寻求结束,如果你想在最后:

fp = open("file_name.gz", "ab+")
fp.seek(0, 2)
fsize = fp.tell()

(当然,如果你只是想知道文件大小,你甚至不需要这个;你可以只fstat文件,或者stat它甚至没有打开它……)


事实上,无论查找位置如何,OS X 和 Linux 都会将所有写入附加到文件末尾。而且我相信他们都会在“a”模式下寻求结束,但在“a+”模式下会做不同的事情。如果您使用的是 Python 2.x,则所有 POSIX 系统上的 open 最终只依赖于 fopen。那么,让我们看看联机帮助页。

Linux fopen(3) :

a+

Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.

苹果 fopen(3)

``a+'' Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.


但细节并不重要;如果您正在编写可移植代码,则不能以这种方式使用 a

关于python - Python 的 tell() 在 Mac OS X 10.8 和 Ubuntu 10.04 上表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19014936/

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