在 python 中写入文件后立即读取时出现意外结果

Unexpected outcome when read right after write a file in python

提问人:23Xor 提问时间:5/25/2023 更新时间:5/25/2023 访问量:17

问:

下面是测试代码:

FILE_PATH = "test.txt"
DEFAULT_TEXT = \
'''123456
456789'''

class FileTest:
    def __init__(self, file_path, default_text, desc):
        self.file_path = file_path
        self.default_text = default_text
        self.desc = desc
    
    def __enter__(self):
        with open(self.file_path, "w") as f:
            f.write(self.default_text)
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Test over.')
        print('--INFO--')
        print('Description:')
        print(self.desc)
        print('File content:')
        with open(self.file_path, "r") as f:
            print(f.read())
        print('--END--')


print('Default file content:')
print(DEFAULT_TEXT)

with FileTest(FILE_PATH, DEFAULT_TEXT, 'control'):
    with open(FILE_PATH, "r+") as f:
        _ = f.write("000")
        _ = f.readline()

with FileTest(FILE_PATH, DEFAULT_TEXT, 'use very small buffer'):
    with open(FILE_PATH, "r+", buffering=2) as f:
        _ = f.write("000")
        _ = f.readline()

with FileTest(FILE_PATH, DEFAULT_TEXT, 'do something between'):
    with open(FILE_PATH, "r+") as f:
        _ = f.write("000")
        _ = f.tell() # f.flush can work as well
        _ = f.readline()

输出:

Default file content:
123456
456789

Test over.
--INFO--
Description:
control
File content:
123456
456789000
--END--

Test over.
--INFO--
Description:
use very small buffer
File content:
000456
456789
--END--

Test over.
--INFO--
Description:
do something between
File content:
000456
456789
--END--

这意味着:默认文件内容:

123456
456789

控制文件内容:
123456
456789000
写在尾部。

使用非常小的缓冲区时的文件内容:
000456
456789
写入头部。

在以下两者之间执行某些操作时的文件内容:
000456
456789
写在头上。

我设置了一个控件来演示意外行为和 2 个可以纠正行为的缓解措施。 在读取和写入之间执行某些操作或设置非常小的缓冲区大小可以使结果正确。

这是python的错误吗?还是 libc 的某些功能?

python-3.x io

评论


答: 暂无答案