文件夹中有上百个文件,现在希望删除包括这些字符的文件标题:
TIMESAVER EDIT -
TIMESAVER EDIT - FULL Q&A Warren Buffett Charlie Munger
TIMESAVER EDIT
TIMESAVER EDIT FULL Q&A Warren Buffett Charlie Munger
在ChatGPT中输入提示词:
你是一个Python编程专家,要完成一个批量删除文件标题中字符的任务,具体步骤如下:
打开本地电脑文件夹: E:\Berkshire Hathaway annual shareholders meeting
获取文件夹中每个文件的标题名称;
如果文件标题中包括“TIMESAVER EDIT - FULL Q&A Warren Buffett Charlie Munger ”或者“TIMESAVER EDIT FULL Q&A Warren Buffett Charlie Munger ”,就从文件标题中删除这些字符;
如果文件标题中不包括“TIMESAVER EDIT - FULL Q&A Warren Buffett Charlie Munger ”或者“TIMESAVER EDIT FULL Q&A Warren Buffett Charlie Munger ”,就继续检查文件标题中是否包括“TIMESAVER EDIT - ”或者TIMESAVER EDIT ,如果有就从文件标题中删除这些字符;
注意:每一步都要输出相关信息
生成Python代码如下:
import os
# 定义要操作的目录和要删除的字符串
directory = r"E:\Berkshire Hathaway annual shareholders meeting"
remove_strings = [
"TIMESAVER EDIT - FULL Q&A Warren Buffett Charlie Munger ",
"TIMESAVER EDIT FULL Q&A Warren Buffett Charlie Munger ",
"TIMESAVER EDIT - ",
"TIMESAVER EDIT "
]
# 遍历文件夹中的所有文件
for filename in os.listdir(directory):
print(f"处理文件: {filename}")
new_filename = filename
# 检查每个要删除的字符串
for remove_string in remove_strings:
if remove_string in new_filename:
print(f"找到匹配: {remove_string}")
new_filename = new_filename.replace(remove_string, "")
# 如果文件名已经被修改,那么重命名文件
if new_filename != filename:
print(f"重命名文件为: {new_filename}")
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))
else:
print("文件名未修改.")
print("处理完成.")
程序运行,打开文件夹,成功批量重命名文件名: