Python脚本实现自动替换文件指定内容
作者:玩人工智能的辣条哥
这篇文章主要为大家详细介绍了如何编写一个py脚本,可以实现自定义替换py文件里面指定内容,感兴趣的小伙伴可以跟随小编一起学习一下
环境
python3.10
问题描述
如何写个py脚本,自定义替换py文件里面指定内容:1.py里面的192.168.1.7:11434替换为192.168.1.7:11435
解决方案
1.单个内容替换,1.py文件里面的192.168.1.7:11434替换为192.168.1.7:11435
import os def replace_content_in_file(file_path, old_string, new_string): """Replace all occurrences of old_string with new_string in the file.""" # Check if the file exists if not os.path.exists(file_path): print(f"文件 {file_path} 不存在") return # Read the content of the file with open(file_path, 'r', encoding='utf-8') as file: content = file.read() # Replace the old string with the new string updated_content = content.replace(old_string, new_string) ```bash # Write the updated content back to the file with open(file_path, 'w', encoding='utf-8') as file: file.write(updated_content) print(f"成功替换 {old_string} 为 {new_string} 在文件 {file_path}") # Specify the file path and strings to replace file_path = '1.py' old_string = '192.168.1.7:11434' new_string = '192.168.1.7:11435' # Call the function to replace content replace_content_in_file(file_path, old_string, new_string)
2.填写具体文件夹路径folder_path = '/home/user/scripts/'下面的1.py文件里面的192.168.1.7:11434替换为192.168.1.7:11435
import os def replace_content_in_file(file_path, old_string, new_string): """Replace all occurrences of old_string with new_string in the file.""" # Check if the file exists if not os.path.exists(file_path): print(f"文件 {file_path} 不存在") return # Read the content of the file with open(file_path, 'r', encoding='utf-8') as file: content = file.read() # Replace the old string with the new string updated_content = content.replace(old_string, new_string) # Write the updated content back to the file with open(file_path, 'w', encoding='utf-8') as file: file.write(updated_content) print(f"成功替换 {old_string} 为 {new_string} 在文件 {file_path}") # Specify the folder path and file name folder_path = '/home/user/scripts/' file_name = '1.py' file_path = os.path.join(folder_path, file_name) # Strings to replace old_string = '192.168.18.7:11434' new_string = '192.168.18.7:11435' # Call the function to replace content replace_content_in_file(file_path, old_string, new_string)
3.不同文件夹多文件替换
import os def replace_content_in_file(file_path, old_string, new_string): """Replace all occurrences of old_string with new_string in the file.""" # Check if the file exists if not os.path.exists(file_path): print(f"文件 {file_path} 不存在") return # Read the content of the file try: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() except Exception as e: print(f"读取文件 {file_path} 时出错: {e}") return # Replace the old string with the new string updated_content = content.replace(old_string, new_string) # Write the updated content back to the file try: with open(file_path, 'w', encoding='utf-8') as file: file.write(updated_content) print(f"成功替换 {old_string} 为 {new_string} 在文件 {file_path}") except Exception as e: print(f"写入文件 {file_path} 时出错: {e}") # Specify the files and their respective folder paths files_to_replace = [ {'folder': '/path/to/w', 'file': '1.py'}, {'folder': '/path/to/x', 'file': '2.py'} ] # Strings to replace old_string = '192.168.16.7:11434' new_string = '192.168.16.7:11435' # Iterate over each file and its folder path for entry in files_to_replace: folder_path = entry['folder'] file_name = entry['file'] file_path = os.path.join(folder_path, file_name) replace_content_in_file(file_path, old_string, new_string)
4.最后脚本
python th.py
import os import chardet def detect_file_encoding(file_path): """检测文件的实际编码""" with open(file_path, 'rb') as file: raw_data = file.read() result = chardet.detect(raw_data) return result['encoding'] def replace_content_in_file(file_path, old_string, new_string): """替换文件中的所有old_string为new_string""" # 检查文件是否存在 if not os.path.exists(file_path): print(f"文件 {file_path} 不存在") return try: # 检测文件编码 encoding = detect_file_encoding(file_path) print(f"检测到文件编码: {encoding}") # 读取文件内容 with open(file_path, 'r', encoding=encoding) as file: content = file.read() print(f"替换前内容:\n{content}") # 替换内容 updated_content = content.replace(old_string, new_string) if updated_content == content: print(f"未找到 {old_string},无需替换") return # 写入更新后的内容 with open(file_path, 'w', encoding=encoding) as file: file.write(updated_content) print(f"成功替换 {old_string} 为 {new_string} 在文件 {file_path}") print(f"替换后内容:\n{updated_content}") except PermissionError: print(f"权限不足,无法访问文件 {file_path}") except Exception as e: print(f"处理文件 {file_path} 时出错: {e}") def main(): # 指定文件和文件夹路径 files_to_replace = [ {'folder': '/mnt/e/work/metahuman-stream/web/realtalk/examples', 'file': 'index.html'}, {'folder': '/mnt/e/work/metahuman-stream/web/realtalk/examples', 'file': 'index_noauto.js'} ] # 要替换的字符串 old_string = '192.168.18.7:11434' new_string = '192.168.18.7:11435' # 遍历每个文件并进行替换 for entry in files_to_replace: folder_path = entry['folder'] file_name = entry['file'] file_path = os.path.join(folder_path, file_name) print(f"\n正在处理文件: {file_path}") replace_content_in_file(file_path, old_string, new_string) if __name__ == "__main__": print("脚本开始执行...") main() print("脚本执行完成。")
以上就是Python脚本实现自动替换文件指定内容的详细内容,更多关于Python替换内容的资料请关注脚本之家其它相关文章!