You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中file.truncate()未按预期截断文件的问题排查

关于Python中file.truncate()行为的疑问

我编写了如下简单的Python程序:

def print_file(filename):    
    with open(filename,'r') as read_file:
        print(read_file.read())

def create_random_file(filename,count):
    with open(filename,'w+', encoding='utf-8') as writefile:
        for row_num in range(count):
            writefile.write(f'{row_num}: fo bar baz\n')

def truncate_file_after_first_line(file,read_a_line):
    file.seek(0,0)  # go to start of file
    print(f"After seeking to 0, at position {file.tell()}");
    if (read_a_line):
        header = file.readline()
        print(f"After reading a line, at position {file.tell()}");
        print(f"Found header '{header.rstrip()}'\n")
    file.write('TRUNCATE AFTER THIS\n')
    print(f"After writing marker, at position {file.tell()}");
    file.truncate()

def mangle_file(filename,read_a_line):
    with open(filename,'r+') as file:
        truncate_file_after_first_line(file,read_a_line)

# ----

filename = 'testpy.txt'
read_a_line = True

create_random_file(filename,5)
print("Original file:")
print_file(filename)
mangle_file(filename,read_a_line)
print("Truncated file:")
print_file(filename)

我的操作流程:

  • 创建一个包含5行内容的文件,并将其内容打印到标准输出;
  • 在mangle_file()函数中:
    • 使用r+模式打开文件(该模式支持读写,流定位在文件开头);
    • 根据布尔值read_a_line的取值,分为两种操作:
      1. 定位到文件开头,读取第一行,写入标记文本“TRUNCATE AFTER THIS\n”,随后调用truncate();
      2. 定位到文件开头,直接写入标记文本,随后调用truncate();
    • 最后关闭文件;
  • 重新读取文件并打印内容。

预期逻辑清晰,但出现异常情况:

  • 当read_a_line=True时(即先读取第一行再执行截断),最终文件内容为原5行内容后追加了标记文本,truncate()未生效;而预期结果应为保留第一行内容并追加标记文本后截断。
  • 当read_a_line=False时,结果符合预期,文件仅保留标记文本。

我添加了file.tell()输出定位信息:

read_a_line=True时的输出:

Original file:
0: fo bar baz
1: fo bar baz
2: fo bar baz
3: fo bar baz
4: fo bar baz

After seeking to 0, at position 0
After reading a line, at position 14
Found header '0: fo bar baz'

After writing marker, at position 90

Truncated file:
0: fo bar baz
1: fo bar baz
2: fo bar baz
3: fo bar baz
4: fo bar baz
TRUNCATE AFTER THIS

read_a_line=False时的输出:

Original file:
0: fo bar baz
1: fo bar baz
2: fo bar baz
3: fo bar baz
4: fo bar baz

After seeking to 0, at position 0
After writing marker, at position 20
Truncated file:
TRUNCATE AFTER THIS

请问我对file.truncate()的理解存在哪些错误?


内容的提问来源于stack exchange,提问作者David Tonhofer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:46:03