Python truncate 函数
最后修改时间:2025 年 3 月 26 日
这份全面的指南探讨了 Python 的 truncate
函数,这是一种用于调整 Python 文件大小的方法。我们将涵盖基本用法、文件定位、上下文管理器和实际应用。通过示例,您将掌握 Python 中的文件截断操作。
基本定义
truncate
方法将文件大小调整为给定的字节数。如果未指定大小,则使用当前文件位置。该方法在以写入或追加模式打开的文件对象上可用。
截断可以缩小或扩展文件。扩展时,新区域将填充空字节。使用 with
语句或调用 flush
后,该操作会立即影响磁盘上的物理文件。
基本截断
truncate
最简单的用法是将文件大小调整为指定的字节大小。此示例显示如何将文件截断为 100 字节。
# Open a file for writing with open('example.txt', 'w') as file: file.write('This is some sample text for demonstration.') # Truncate the file to 10 bytes with open('example.txt', 'r+') as file: file.truncate(10) print(file.read()) # Output: 'This is so'
此代码首先创建一个包含示例文本的文件,然后将其截断为 10 字节。 r+
模式允许读取和写入。截断后,文件中只保留前 10 个字节。
请注意,truncate 基于字节数而不是字符数进行操作。对于 UTF-8 等多字节编码,这可能会在字符中间分割字符。处理文本文件时,始终考虑文件编码。
在当前位置截断
在不带参数的情况下调用时,truncate
使用当前文件位置作为新大小。此示例演示了基于位置的截断。
# Create a sample file with open('data.txt', 'w') as file: file.write('Line 1\nLine 2\nLine 3\nLine 4\n') # Truncate after second line with open('data.txt', 'r+') as file: file.readline() # Read first line file.readline() # Read second line file.truncate() # Truncate at current position file.seek(0) print(file.read()) # Output: 'Line 1\nLine 2\n'
此示例从文件中读取两行,然后在该位置截断。截断后,剩余内容仅包含前两行。 seek(0)
调用返回到开头进行读取。
此技术对于处理要在某个点之后删除内容的文件非常有用。它通常用于日志轮换和数据处理场景。
使用 Truncate 扩展文件
truncate
还可以通过指定大于当前文件大小的大小来扩展文件。 新空间填充空字节。
# Create a small file with open('small.txt', 'w') as file: file.write('abc') # Extend the file to 10 bytes with open('small.txt', 'r+') as file: file.truncate(10) print(f"File size: {file.tell()} bytes") file.seek(0) content = file.read() print(f"Content: {content!r}") # Output: 'abc\x00\x00\x00\x00\x00\x00\x00'
此代码创建一个 3 字节的文件,然后将其扩展到 10 字节。新空间包含空字节 (\x00
)。格式字符串中的 !r
显示内容的原始表示形式。
使用 truncate 扩展文件在为以后填充的文件预先分配空间时非常有用。 它可以通过确保连续的磁盘空间分配来提高性能。
截断二进制文件
truncate
方法同样适用于二进制文件。此示例显示了在特定位置截断二进制文件。
# Create a binary file with sample data with open('data.bin', 'wb') as file: file.write(bytes(range(100))) # 0 to 99 # Truncate to first 50 bytes with open('data.bin', 'r+b') as file: file.truncate(50) print(f"File size: {file.tell()} bytes") content = file.read() print(f"First byte: {content[0]}, Last byte: {content[-1]}") # Output: First byte: 0, Last byte: 49
此示例创建一个包含 100 个字节(值 0-99)的二进制文件,然后将其截断为 50 个字节。 r+b
模式以二进制模式打开文件以进行读取和写入。二进制模式对于非文本文件至关重要。
处理二进制文件时,截断通常用于删除损坏的数据或提取文件的特定部分。字节级精度使其成为二进制格式的理想选择。
在追加模式下截断
虽然通常与读写模式一起使用,但 truncate
也可以在追加模式(a
或 a+
)中使用。 此示例显示了如何组合追加和截断。
# Create initial file with open('log.txt', 'w') as file: file.write('Log entry 1\nLog entry 2\nLog entry 3\n') # Append and then truncate with open('log.txt', 'a+') as file: file.write('Log entry 4\n') file.seek(0) # Move to start for truncation file.truncate(20) # Keep first 20 bytes file.seek(0) print(file.read()) # Output: 'Log entry 1\nLog ent'
此示例演示了即使在追加模式下,您也可以搜索到其他位置并执行截断。 a+
模式允许追加和读取,但写入始终最初转到末尾。
此技术对于日志轮换非常有用,您可以在其中添加新条目但限制总文件大小。 请记住,在追加模式下搜索需要 a+
而不仅仅是 a
。
最佳实践
- 使用上下文管理器:始终首选
with
语句进行文件处理 - 备份重要文件:截断具有破坏性 - 考虑备份
- 检查文件位置:在不使用 size 参数进行截断之前,验证位置
- 处理异常:捕获文件操作的 IOError/OSError
- 考虑编码:对于文本文件,请注意多字节字符
资料来源
作者
列出所有 Python 教程。