我目前正在使用 python-fuse 制作一个文件系统,并正在查找每种不同模式(“r”、“r+”等)的文件指针的起始位置,并在多个站点上找到文件指针的起始位置在零,除非它在文件末尾开始时以 'a' 或 'a+' 打开。
我在 Python 中对此进行了测试以确保(在每种模式下打开一个文本文件并立即调用 tell())但是发现当它在 'a+' 中打开时文件指针为零而不是结尾文件。
这是 python 中的错误,还是网站有误?
供引用:
- one of the websites (搜索“文件指针”)
- 我在 Ubuntu 上使用 Python 2.7.3
最佳答案
不,这不是错误。
当您调用 tell()
after 写入一些数据时会发生什么?
它是在位置 0 处写入,还是像您预期的那样在文件末尾写入?我几乎敢打赌是后者。
>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
15
>>> f.close()
>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
30
因此,它确实会在写入数据之前寻找到文件末尾。
这是应该的。来自 fopen()
手册页:
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.
呸,幸运的是我是对的。
关于python - Python 的 'a+' 文件打开模式中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016825/