Python腳本實現(xiàn)自動替換文件指定內(nèi)容
環(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+django+sql學(xué)生信息管理后臺開發(fā)
這篇文章主要為大家詳細(xì)介紹了python+django+sql學(xué)生信息管理后臺開發(fā),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01PyTorch?Dataset與DataLoader使用超詳細(xì)講解
用于處理數(shù)據(jù)樣本的代碼可能會變得凌亂且難以維護(hù);理想情況下,我們希望數(shù)據(jù)集代碼與模型訓(xùn)練代碼解耦,以獲得更好的可讀性和模塊化。PyTorch提供的torch.utils.data.DataLoader和torch.utils.data.Dataset允許你使用預(yù)下載的數(shù)據(jù)集或自己制作的數(shù)據(jù)2022-10-10python實現(xiàn)圖片轉(zhuǎn)字符畫的完整代碼
這篇文章主要給大家介紹了關(guān)于python實現(xiàn)圖片轉(zhuǎn)字符畫的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02解決python3.5 正常安裝 卻不能直接使用Tkinter包的問題
今天小編就為大家分享一篇解決python3.5 正常安裝 卻不能直接使用Tkinter包的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02