下面是一个示例代码,用于移动包含特定字符串的文件:
import os
import shutil
def move_files_with_string(source_dir, dest_dir, search_string):
# 遍历源文件夹中的所有文件
for root, dirs, files in os.walk(source_dir):
for file in files:
# 判断文件名是否包含特定字符串
if search_string in file:
source_path = os.path.join(root, file)
dest_path = os.path.join(dest_dir, file)
# 移动文件
shutil.move(source_path, dest_path)
print(f"Moved file: {file}")
# 设置源文件夹路径
source_dir = "/path/to/source/directory"
# 设置目标文件夹路径
dest_dir = "/path/to/destination/directory"
# 设置要搜索的特定字符串
search_string = "example"
# 调用函数移动文件
move_files_with_string(source_dir, dest_dir, search_string)
将上述代码中的/path/to/source/directory
替换为源文件夹的实际路径,/path/to/destination/directory
替换为目标文件夹的实际路径,example
替换为要搜索的特定字符串。
这段代码将遍历源文件夹中的所有文件,如果文件名中包含特定字符串,则将文件移动到目标文件夹中。移动文件使用了shutil.move()
函数。在移动文件之前,可以根据需要添加其他逻辑或条件判断。