将多个路径下文件批量复制到另外一个路径下并重命名
时间: 2024-04-08 14:29:44 浏览: 13
您可以使用Python的`shutil`模块来实现将多个路径下的文件批量复制到另外一个路径下并重命名的功能。以下是示例代码:
```python
import os
import shutil
def copy_and_rename_files(source_paths, destination_path, new_names):
for i, path in enumerate(source_paths):
# 检查源文件是否存在
if not os.path.exists(path):
print(f"File does not exist: {path}")
continue
# 提取源文件名和扩展名
file_name, file_ext = os.path.splitext(os.path.basename(path))
# 构造新的文件名
new_name = new_names[i]
new_file_name = f"{new_name}{file_ext}"
# 构造目标路径
destination = os.path.join(destination_path, new_file_name)
# 复制并重命名文件
shutil.copy2(path, destination)
print(f"File copied and renamed: {destination}")
# 源文件路径列表
source_paths = [
'path/to/file1.txt',
'path/to/file2.txt',
'path/to/file3.txt'
]
# 目标路径
destination_path = 'path/to/destination/'
# 新文件名列表
new_names = [
'new_file1',
'new_file2',
'new_file3'
]
# 调用函数进行批量复制和重命名
copy_and_rename_files(source_paths, destination_path, new_names)
```
请将上述代码中的`source_paths`、`destination_path`和`new_names`替换为您实际的路径和文件名。这样,您就可以将多个源路径下的文件批量复制到目标路径下并重命名了。