用ChatGPT進行批量重命名時,,一部分成功了,但有一部分文件標(biāo)題沒有變化,。 問下ChatGPT怎么回事: 回復(fù):在Windows中,,文件名不能包含以下字符:\ / : * ? " < > |,使用Python的 str.replace 方法來替換Excel文件的第1列中不能用于文件名的字符 于是,,把這個注意事項加入到提示詞中: 你是一個Python編程專家,,要完成批量重命名的任務(wù),具體步驟如下: 讀取F盤的表格文件:pname.xlsx,,獲取到第2列的數(shù)據(jù),; 逐一讀取文件夾“D:\lexfridman-podcast”里面的所有mp3文件的名稱,然后和表格pname.xlsx第2列所有內(nèi)容進行比對,,如果和某個單元格內(nèi)容一致,,則讀取這個單元格同一行的第1列單元格的內(nèi)容,以此對文件標(biāo)題進行重命名,; 注意:每一步都要輸出相關(guān)信息,; 在Windows中,文件名不能包含以下字符:\ / : * ? " < > |,,使用Python的 str.replace 方法來替換Excel文件的第1列中不能用于文件名的字符 這次給出的源代碼運行成功: import os import pandas as pd # 讀取Excel文件 df = pd.read_excel('F:\\pname.xlsx', usecols=[0, 1], header=None) # 獲取文件夾中的所有文件 folder_path = 'D:\\lexfridman-podcast' files = os.listdir(folder_path) # 定義一個函數(shù),,它會將所有不能用于文件名的字符替換為下劃線 "_" def sanitize_filename(filename): invalid_chars = '\\/:*?"<>|' for char in invalid_chars: filename = filename.replace(char, '_') return filename # 遍歷文件夾中的每一個文件 for file in files: # 檢查文件是否是mp3文件 if file.endswith('.mp3'): # 去掉".mp3"后綴,方便比較 file_without_extension = file[:-4] # 查找這個文件名在Excel表格的第二列(Python中索引從0開始)中的位置 matching_rows = df[df[1] == file_without_extension] # 如果找到了匹配的行 if not matching_rows.empty: # 獲取新的名字,,并清理無效的字符 new_name = sanitize_filename(matching_rows.iloc[0, 0]) + ".mp3" # 輸出信息 print(f"Renaming {file} to {new_name}") # 重命名文件 os.rename(os.path.join(folder_path, file), os.path.join(folder_path, new_name)) # 完成后輸出信息 print("All files have been renamed.") |
|