最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python腳本實現(xiàn)自動替換文件指定內(nèi)容

 更新時間:2025年03月03日 09:39:18   作者:玩人工智能的辣條哥  
這篇文章主要為大家詳細(xì)介紹了如何編寫一個py腳本,可以實現(xiàn)自定義替換py文件里面指定內(nèi)容,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

環(huán)境

python3.10

問題描述

如何寫個py腳本,自定義替換py文件里面指定內(nèi)容:1.py里面的192.168.1.7:11434替換為192.168.1.7:11435

解決方案

1.單個內(nèi)容替換,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}")
        
        # 讀取文件內(nèi)容
        with open(file_path, 'r', encoding=encoding) as file:
            content = file.read()
            print(f"替換前內(nèi)容:\n{content}")
        
        # 替換內(nèi)容
        updated_content = content.replace(old_string, new_string)
        if updated_content == content:
            print(f"未找到 {old_string},無需替換")
            return
        
        # 寫入更新后的內(nèi)容
        with open(file_path, 'w', encoding=encoding) as file:
            file.write(updated_content)
        
        print(f"成功替換 {old_string} 為 {new_string} 在文件 {file_path}")
        print(f"替換后內(nèi)容:\n{updated_content}")
    
    except PermissionError:
        print(f"權(quán)限不足,無法訪問文件 {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'
    # 遍歷每個文件并進(jìn)行替換
    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("腳本開始執(zhí)行...")
    main()
    print("腳本執(zhí)行完成。")

以上就是Python腳本實現(xiàn)自動替換文件指定內(nèi)容的詳細(xì)內(nèi)容,更多關(guān)于Python替換內(nèi)容的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 教你python 中如何取出colomap部分的顏色范圍

    教你python 中如何取出colomap部分的顏色范圍

    這篇文章主要介紹了python 中如何取出colomap部分的顏色范圍,本文以以jet為例給大家提供一種方法,可以提取colormap色標(biāo)中的一部分,取出我們滿意的色標(biāo)區(qū)域,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • Python庫BeautifulSoup中的select()和select_one()有什么區(qū)別

    Python庫BeautifulSoup中的select()和select_one()有什么區(qū)別

    BeautifulSoup是一個強(qiáng)大且易于使用的Python庫,它能夠解析HTML和XML文檔,并提供了一系列便捷的方法來提取所需的數(shù)據(jù),其中,`select()`和`select_one()`?允許我們使用?CSS?選擇器來定位文檔中的元素,本文將深入探討這兩個函數(shù)的使用方法、區(qū)別以及實際應(yīng)用場景
    2025-06-06
  • python中日期和時間格式化輸出的方法小結(jié)

    python中日期和時間格式化輸出的方法小結(jié)

    這篇文章主要介紹了python中日期和時間格式化輸出的方法,實例總結(jié)了Python常見的日期與事件操作技巧,非常具有實用價值,需要的朋友可以參考下
    2015-03-03
  • 詳解Python中的Numpy、SciPy、MatPlotLib安裝與配置

    詳解Python中的Numpy、SciPy、MatPlotLib安裝與配置

    這篇文章主要介紹了詳解Python中的Numpy、SciPy、MatPlotLib安裝與配置,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • 利用python下載scihub成文獻(xiàn)為PDF操作

    利用python下載scihub成文獻(xiàn)為PDF操作

    這篇文章主要介紹了利用python下載scihub成文獻(xiàn)為PDF操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • python pygame入門教程

    python pygame入門教程

    pygame是python的游戲編程模塊,今天我們就來一起簡單的學(xué)習(xí)如何使用該模塊
    2021-06-06
  • Python 多進(jìn)程并發(fā)操作中進(jìn)程池Pool的實例

    Python 多進(jìn)程并發(fā)操作中進(jìn)程池Pool的實例

    下面小編就為大家?guī)硪黄狿ython 多進(jìn)程并發(fā)操作中進(jìn)程池Pool的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • Python中修改字符串的四種方法

    Python中修改字符串的四種方法

    在Python中,字符串是不可變類型,即無法直接修改字符串的某一位字符。這篇文章主要介紹了Python中修改字符串的四種方法,需要的朋友可以參考下
    2018-11-11
  • Python+tkinter自定義實現(xiàn)文件選擇按鈕

    Python+tkinter自定義實現(xiàn)文件選擇按鈕

    這篇文章主要為大家詳細(xì)介紹了如何利用Python和tkinter自定義實現(xiàn)簡單的文件選擇按鈕和顏色選擇按鈕,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-10-10
  • selenium+python自動化測試之環(huán)境搭建

    selenium+python自動化測試之環(huán)境搭建

    這篇文章主要介紹了selenium+python自動化測試之環(huán)境搭建,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01

最新評論

仁化县| 乌拉特前旗| 丹凤县| 永靖县| 富平县| 丽水市| 汝南县| 巴南区| 长春市| 宁化县| 白朗县| 五台县| 应用必备| 鹿邑县| 阿克苏市| 古田县| 耒阳市| 确山县| 六安市| 阜城县| 宕昌县| 沙田区| 朔州市| 疏附县| 西藏| 江都市| 扶沟县| 岳西县| 大冶市| 庄河市| 芒康县| 青岛市| 昔阳县| 乡城县| 保康县| 忻州市| 仪陇县| 武义县| 白朗县| 义乌市| 宝鸡市|