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

如何用Python替换文件夹中.c/.h文件里的"Version1"为"Version2.2.1"?

Got it, let's solve this batch replacement problem for your C/C++ header and source files. Below is a practical Python script that gets the job done, plus breakdowns of how each part works so you can tweak it if needed:

Python Script for Batch Version String Replacement
import os

def batch_replace_version(folder_path, old_str, new_str):
    # Recursively walk through all directories and files in the target folder
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            # Only process .c and .h files
            if file.endswith(('.c', '.h')):
                file_full_path = os.path.join(root, file)
                try:
                    # Read the file content
                    with open(file_full_path, 'r', encoding='utf-8') as input_file:
                        file_content = input_file.read()
                    
                    # Skip files that don't contain the old string to save unnecessary writes
                    if old_str not in file_content:
                        continue
                    
                    # Perform the replacement
                    updated_content = file_content.replace(old_str, new_str)
                    
                    # Write the updated content back to the file
                    with open(file_full_path, 'w', encoding='utf-8') as output_file:
                        output_file.write(updated_content)
                    
                    print(f"Updated successfully: {file_full_path}")
                except Exception as error:
                    print(f"Failed to process {file_full_path}: {str(error)}")

if __name__ == "__main__":
    # Replace this with your actual target folder path
    target_directory = "/path/to/your/folder"
    old_version_string = "Version1"
    new_version_string = "Version2.2.1"
    
    batch_replace_version(target_directory, old_version_string, new_version_string)
    print("Batch replacement process finished!")
Key Details & Explanations
  • Recursive Directory Traversal: os.walk() goes through every subfolder under your target directory, so you won't miss any nested .c/.h files.
  • File Type Filtering: The endswith(('.c', '.h')) check ensures we only modify the file types you care about—no accidental changes to other files.
  • Encoding Handling: We use utf-8 encoding by default, but if your files use a different encoding (like GBK for some Chinese-language projects), swap it out here to avoid garbled text.
  • Efficient Writes: We skip writing to files that don't have the Version1 string, which saves time and reduces disk I/O.
  • Error Resilience: The try-except block catches issues like permission errors or corrupted files, so the script won't crash halfway through processing.
Important Pre-Run Notes
  • Backup First!: Always make a copy of your target folder before running the script. Even with safeguards, it's better to be safe than sorry if something unexpected happens.
  • Test with a Sample: Try running the script on a small test folder with a few .c/.h files first to verify the replacement works as expected.
  • Path Formatting: On Windows, use double backslashes ("C:\\your\\folder\\path") or raw strings (r"C:\your\folder\path") to avoid path escape issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:40:04