杰瑞科技汇

Python如何替换txt文件内容?

Of course! Replacing text in a .txt file is a common task in Python. The general approach is to:

Python如何替换txt文件内容?-图1
(图片来源网络,侵删)
  1. Read the content of the file into a string variable.
  2. Replace the old text with the new text using Python's built-in .replace() string method.
  3. Write the modified content back to the file (often by overwriting the original file).

Here are the most common methods, from the simplest to the most robust.


Method 1: The Simple & Direct Approach

This method is great for small files where you don't need to worry about encoding or accidentally corrupting the file if the script is interrupted. It reads the whole file into memory, modifies it, and writes it back.

Code:

def replace_in_file_simple(file_path, old_text, new_text):
    """
    Reads a file, replaces text, and writes it back.
    Suitable for small files.
    """
    try:
        # 1. Read the entire content of the file
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        # 2. Replace the old text with the new text
        modified_content = content.replace(old_text, new_text)
        # 3. Write the modified content back to the file
        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(modified_content)
        print(f"Successfully replaced '{old_text}' with '{new_text}' in '{file_path}'")
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")
# --- Example Usage ---
# First, let's create a sample file
sample_file = "my_document.txt"
with open(sample_file, 'w', encoding='utf-8') as f:
    f.write("Hello World.\nThis is a test file.\nHello again, World!")
print("--- Before replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())
# Now, let's replace "World" with "Python"
replace_in_file_simple(sample_file, "World", "Python")
print("\n--- After replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())

Output of the example:

Python如何替换txt文件内容?-图2
(图片来源网络,侵删)
--- Before replacement ---
Hello World.
This is a test file.
Hello again, World!
--- After replacement ---
Hello Python.
This is a test file.
Hello again, Python!

Method 2: The Safer "Read/Write to a Temporary File" Approach

This is the recommended method for most use cases. It's much safer because it first writes the modified content to a temporary file. Only after the new file is successfully created does it replace the original file. This prevents data corruption if the script crashes midway.

Code:

import os
import shutil
def replace_in_file_safe(file_path, old_text, new_text):
    """
    Safely replaces text in a file using a temporary file.
    This is the recommended approach.
    """
    temp_path = file_path + ".tmp"
    try:
        # 1. Read from the original file and write to a temporary file
        with open(file_path, 'r', encoding='utf-8') as original_file, \
             open(temp_path, 'w', encoding='utf-8') as temp_file:
            for line in original_file:
                # Replace text in each line before writing
                modified_line = line.replace(old_text, new_text)
                temp_file.write(modified_line)
        # 2. Replace the original file with the temporary file
        # On Windows, you might need os.replace() instead of shutil.move()
        shutil.move(temp_path, file_path)
        print(f"Successfully and safely replaced '{old_text}' with '{new_text}' in '{file_path}'")
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
        # Clean up the temp file if it was created
        if os.path.exists(temp_path):
            os.remove(temp_path)
    except Exception as e:
        print(f"An error occurred: {e}")
        # Clean up the temp file if it was created
        if os.path.exists(temp_path):
            os.remove(temp_path)
# --- Example Usage ---
# Re-create the sample file
with open(sample_file, 'w', encoding='utf-8') as f:
    f.write("Hello World.\nThis is a test file.\nHello again, World!")
print("--- Before safe replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())
# Now, let's replace "Hello" with "Greetings"
replace_in_file_safe(sample_file, "Hello", "Greetings")
print("\n--- After safe replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())

Why is this safer?

  • Atomicity (mostly): If your computer loses power while the script is running, you will either have the original file or the new, correct file. You won't end up with a half-written, corrupted file.
  • Line-by-line processing: This method reads the file line by line, which is more memory-efficient for very large files that might not fit into your computer's RAM.

Method 3: Advanced - Using Regular Expressions (Regex)

If your replacement needs are more complex (e.g., case-insensitive replacement, replacing patterns, not just fixed strings), you should use Python's re module.

Python如何替换txt文件内容?-图3
(图片来源网络,侵删)

Example: Case-Insensitive Replacement

import re
def replace_in_file_regex(file_path, old_pattern, new_text, flags=0):
    """
    Replaces text in a file using regular expressions.
    The 'flags' argument can be re.IGNORECASE for case-insensitive replacement.
    """
    temp_path = file_path + ".tmp"
    try:
        with open(file_path, 'r', encoding='utf-8') as original_file, \
             open(temp_path, 'w', encoding='utf-8') as temp_file:
            for line in original_file:
                # Use re.sub() for regex-based replacement
                modified_line = re.sub(old_pattern, new_text, line, flags=flags)
                temp_file.write(modified_line)
        shutil.move(temp_path, file_path)
        print(f"Successfully used regex to replace '{old_pattern}' with '{new_text}' in '{file_path}'")
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except Exception as e:
        print(f"An error occurred: {e}")
# --- Example Usage ---
# Re-create the sample file
with open(sample_file, 'w', encoding='utf-8') as f:
    f.write("Hello world.\nThis is a test file.\nWORLD is amazing.")
print("--- Before regex replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())
# Replace "world" (case-insensitive) with "Earth"
replace_in_file_regex(sample_file, "world", "Earth", flags=re.IGNORECASE)
print("\n--- After regex replacement ---")
with open(sample_file, 'r', encoding='utf-8') as f:
    print(f.read())

Output of the regex example:

--- Before regex replacement ---
Hello world.
This is a test file.
WORLD is amazing.
--- After regex replacement ---
Hello Earth.
This is a test file.
EARTH is amazing.

Summary: Which Method to Choose?

Method Best For Pros Cons
Simple Quick scripts, small files, learning. Very easy to write and understand. Unsafe for large/critical files; can corrupt data on crash.
Safe (Temp File) Most production scripts. Safe, memory-efficient for large files. Slightly more code than the simple method.
Regex Complex patterns, case-insensitivity, etc. Extremely powerful and flexible. Overkill for simple replacements; can be slower.
分享:
扫描分享到社交APP
上一篇
下一篇