Unknown model· unknown
from ShareGPT 90K (shared ChatGPT conversations)
請你扮演一個python專家,寫一個python程式。程式的功能如下: 1. 輸入一張png檔案為byte[] 2. 在這個byte[]中尋找特定的連續序列…
- User
請你扮演一個python專家,寫一個python程式。程式的功能如下:
- 輸入一張png檔案為byte[]
- 在這個byte[]中尋找特定的連續序列 "123123",這個序列在檔案中只會出現一次
- 將這個byte序列位置取代填入由"000001"至"000999"的號碼,loop產出999個檔案
- 將999個結果寫為新檔案
- Assistant
以下是一個滿足需求的Python程式碼:
pythonimport os def replace_sequence_in_file(input_file_path): # 讀取檔案 with open(input_file_path, 'rb') as f: file_bytes = bytearray(f.read()) # 尋找目標序列 target_sequence = b'123123' start_index = file_bytes.find(target_sequence) # 如果找不到目標序列,則返回None if start_index == -1: return None # 取代目標序列為數字 for i in range(1, 1000): number = str(i).zfill(6).encode() file_bytes[start_index:start_index+len(target_sequence)] = number # 將結果寫入新檔案 output_file_path = f"{os.path.splitext(input_file_path)[0]}_{i}{os.path.splitext(input_file_path)[1]}" with open(output_file_path, 'wb') as f: f.write(file_bytes) return output_file_path # 測試程式碼 input_file_path = "example.png" output_file_path = replace_sequence_in_file(input_file_path) if output_file_path is None: print("找不到目標序列") else: print(f"成功產生999個新檔案,儲存位置為{os.path.dirname(output_file_path)}")