杰瑞科技汇

Python file truncate如何精确控制文件截断长度?

Of course! In Python, "truncating" a file means reducing its size to a specific number of bytes, or to zero bytes (making it empty). This is a common operation, especially in logging or when you want to reset a file's contents without deleting and recreating it.

Python file truncate如何精确控制文件截断长度?-图1
(图片来源网络,侵删)

The primary and most efficient way to do this is using the truncate() method on a file object.

The Main Method: fileobject.truncate(size)

When you open a file in a mode that allows writing ('w', 'r+', 'a+', 'w+'), you can call the .truncate() method on the returned file object.

Syntax

file_object.truncate(size)
  • size (optional): The target size of the file in bytes.
    • If size is omitted, the file is truncated at the current cursor position.
    • If size is specified, the file is truncated to that size.
    • If size is larger than the current file size, the file is padded with null bytes (\x00) up to the specified size.

Key Scenarios for Truncating

Let's break down the most common use cases.

Scenario 1: Truncating to Zero Bytes (Making a File Empty)

This is the most common use case. You want to clear the contents of a file but keep the file itself.

Python file truncate如何精确控制文件截断长度?-图2
(图片来源网络,侵删)

How it works:

  1. Open the file in a mode that allows both reading and writing. 'w+' is a good choice, but 'r+' is often safer because it won't destroy the file's contents if the file doesn't exist (it will raise an error instead).
  2. Call .truncate() with no arguments. This truncates the file from the current cursor position (which is at the beginning, 0) to the end of the file.
  3. Important: The file's cursor is now at the end of the (now empty) file. If you want to write new content, you must move the cursor back to the beginning using file_object.seek(0).

Example:

Let's say we have a file named data.txt with the following content:

Hello, World!
This is some text.

Here is the Python code to empty it:

Python file truncate如何精确控制文件截断长度?-图3
(图片来源网络,侵删)
# The 'r+' mode opens for reading and writing.
# It will raise an error if the file doesn't exist, which is often desirable.
try:
    with open('data.txt', 'r+') as f:
        print(f"File size before truncation: {f.tell()} bytes") # Cursor is at 0
        f.truncate() # Truncate from current position (0) to the end
        print(f"File size after truncation: {f.tell()} bytes") # Cursor is still at 0
        # Now let's write new content to the empty file
        f.seek(0) # Move cursor to the beginning of the file
        f.write("The file has been truncated and rewritten.")
except FileNotFoundError:
    print("Error: The file does not exist.")
# Let's verify the result
with open('data.txt', 'r') as f:
    content = f.read()
    print("\n--- Final Content of data.txt ---")
    print(content)

Output:

File size before truncation: 0 bytes
File size after truncation: 0 bytes
--- Final Content of data.txt ---
The file has been truncated and rewritten.

Scenario 2: Truncating to a Specific Size

Sometimes you don't want to delete everything, just remove the end of the file.

How it works:

  1. Open the file in a read/write mode ('r+' or 'w+').
  2. Call .truncate(size) where size is the new length in bytes.

Example:

Let's use the same data.txt:

Hello, World!
This is some text.

We want to keep only the first 13 bytes (which is "Hello, World!").

with open('data.txt', 'r+') as f:
    # Get the current size to inform the user
    f.seek(0, 2) # Go to the end of the file to find its size
    original_size = f.tell()
    print(f"Original file size: {original_size} bytes")
    # Truncate the file to 13 bytes
    f.truncate(13)
    print(f"New file size: {f.tell()} bytes") # Cursor is now at 13
# Let's verify the result
with open('data.txt', 'r') as f:
    content = f.read()
    print("\n--- Final Content of data.txt ---")
    print(repr(content)) # Using repr to show any special characters

Output:

Original file size: 27 bytes
New file size: 13 bytes
--- Final Content of data.txt ---
'Hello, World!'

Notice the second line of the file is gone.


Important Considerations

File Opening Mode

You cannot truncate a file opened in read-only mode ('r'). You must use a mode that allows writing.

Mode Read Write Create Truncate? Common Use for Truncate
'r' No
'w' Yes* Yes (but empties file first)
'a' No (appends instead)
'r+' Yes Best for truncating
'w+' Yes* Yes (but empties file first)
'a+' No (appends instead)

*The 'w' and 'w+' modes automatically truncate the file to zero bytes when you open it. This is different from calling .truncate() on an open file.

File Cursor Position

The behavior of truncate() depends entirely on where the file's cursor is located.

  • f.truncate(): Truncates from the current cursor position to the end of the file.
  • f.truncate(100): Sets the file size to 100 bytes. If the cursor was beyond 100, it's moved back to 100.

This is why in the examples, we often use f.seek(0) before truncating if we want to clear the file from the very beginning.

Atomicity and Race Conditions

For simple scripts, truncate() is perfect. However, in high-concurrency applications (like a web server), you must be careful. If two processes try to read and write the same file at the same time, you can get corrupted data. For such cases, you might need to use file locking mechanisms or atomic operations provided by the OS. For most use cases, this is not a concern.

Summary

Goal Method Example
Make a file empty Open in 'r+' and call truncate() with open('file.txt', 'r+') as f: f.truncate()
Keep only the first N bytes Open in 'r+' and call truncate(N) with open('file.txt', 'r+') as f: f.truncate(100)
Delete the last part of a file Open in 'r+', seek to the desired point, then truncate() with open('file.txt', 'r+') as f: f.seek(50); f.truncate()
分享:
扫描分享到社交APP
上一篇
下一篇