如何写一个python脚本,自定义替换.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("脚本执行完成。")




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玩人工智能的辣条哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值