Python脚本实现自动替换文件指定内容

 更新时间:2025年03月03日 09:39:18   作者:玩人工智能的辣条哥  
这篇文章主要为大家详细介绍了如何编写一个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替换内容的资料请关注脚本之家其它相关文章!

相关文章

  • python+django+sql学生信息管理后台开发

    python+django+sql学生信息管理后台开发

    这篇文章主要为大家详细介绍了python+django+sql学生信息管理后台开发,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • PyCharm 常用快捷键和设置方法

    PyCharm 常用快捷键和设置方法

    下面小编就为大家分享一篇PyCharm 常用快捷键和设置方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • 8个Python编程进阶常用技巧分享

    8个Python编程进阶常用技巧分享

    介绍 Python 炫酷功能的文章层出不穷,但是还有很多 Python 的编程小技巧鲜被提及,所以本文会试着介绍一些其它文章没有提到的小技巧,让我们一探究竟吧
    2023-07-07
  • Python写的一个简单监控系统

    Python写的一个简单监控系统

    这篇文章主要介绍了Python写的一个简单监控系统,本文讲解了详细的编码步骤,并给给出相应的实现代码,需要的朋友可以参考下
    2015-06-06
  • PyCharm中找不到pandas库的问题解决

    PyCharm中找不到pandas库的问题解决

    本文主要介绍了PyCharm中找不到pandas库的问题解决,文中通过几种解决方法介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2025-04-04
  • Django admin美化插件suit使用示例

    Django admin美化插件suit使用示例

    这篇文章主要介绍了Django admin美化插件suit使用示例,简单介绍了suit的使用界面示例,官方文档,安装语句等相关内容,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • PyTorch Dataset与DataLoader使用超详细讲解

    PyTorch Dataset与DataLoader使用超详细讲解

    用于处理数据样本的代码可能会变得凌乱且难以维护;理想情况下,我们希望数据集代码与模型训练代码解耦,以获得更好的可读性和模块化。PyTorch提供的torch.utils.data.DataLoader和torch.utils.data.Dataset允许你使用预下载的数据集或自己制作的数据
    2022-10-10
  • python实现图片转字符画的完整代码

    python实现图片转字符画的完整代码

    这篇文章主要给大家介绍了关于python实现图片转字符画的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • python爬取足球直播吧五大联赛积分榜

    python爬取足球直播吧五大联赛积分榜

    这篇文章主要为大家详细介绍了python爬取足球直播吧五大联赛积分榜,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-06-06
  • 解决python3.5 正常安装 却不能直接使用Tkinter包的问题

    解决python3.5 正常安装 却不能直接使用Tkinter包的问题

    今天小编就为大家分享一篇解决python3.5 正常安装 却不能直接使用Tkinter包的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-02-02

最新评论