如何将一堆同名文件复制到一个文件夹?

How to copy a bunch of files with same name to a folder?

我有一些文件的扩展名不同。 这些文件位于不同的文件夹中并且具有相同的名称。 我想复制这些文件并同时重命名它们。

我有:

我想将其重命名为:

PS: 我会在这个新文件夹中有几个相同类型的文件

我研究并找到了 Shutil 库来编写代码,但我遇到了麻烦。有人有什么想法可以开始吗?

这是我试过的

# importing os module
import os

# importing shutil module
import shutil

# path
path = r'D:\Usuarios[=10=]25429\Desktop\old_folder'

# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))

# Source path
source = r"D:\Usuarios[=10=]25429\Desktop\old_folder\IQ.txt"
source = r"D:\Usuarios[=10=]25429\Desktop\old_folder\IQ.xlsx"
source = r"D:\Usuarios[=10=]25429\Desktop\old_folder\IQ.docx"
# Print file permission
# of the source
perm = os.stat(source).st_mode
print("File Permission mode:", perm, "\n")

# Destination path
destination = r"D:\Usuarios[=10=]25429\Desktop\new_folder"

# Copy the content of
# source to destination
dest = shutil.copy(source, destination)
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))

# Print file permission
# of the destination
perm = os.stat(destination).st_mode
print("File Permission mode:", perm)

# Print path of newly
# created file
print("Destination path:", dest)

您可以使用 shutil 中的 pathlib to work with filesystem and copy() 来复制每个文件。

from shutil import copy
from pathlib import Path

src = Path(r".\dir1")
dst = Path(r".\dir2")
idx = 0
for file in src.iterdir():
    if file.is_file():
        idx += 1
        copy(file, (dst / f"Archive_{idx}").with_suffix(file.suffix))

要仅重命名具有给定名称的文件,请使用下一个代码:

from shutil import copy
from pathlib import Path

src = Path(r".\dir1")
filename = "123"
dst = Path(r".\dir2")
idx = 0
for file in src.iterdir():
    if file.is_file() and file.stem == filename:
        idx += 1
        copy(file, (dst / f"Archive_{idx}").with_suffix(file.suffix))