将文件从源文件复制到目标文件,并附加目标文件名



尝试根据类型将特定文件从源目录复制到目标目录。我想重命名目标文件,因为它从源复制到包括其父文件夹(S:folder_name - file_name.pdf)。这是我到目前为止所拥有的,它似乎复制了预期的文件,但我不知道如何根据源文件文件夹位置重命名目标文件。

import os
import shutil as sh
root_path = (r"S:Colocation Information Kory.Williams@charter.com )")
dest_path = (r"C:UsersP2187119DocumentsMSA_SO Crawl")
for dirpath, dnames, fnames in os.walk(root_path):
for f in fnames:
if f.endswith(".pdf"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f}this is my location from pdf")
elif f.endswith(".doc"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f} this is my location from doc")
elif f.endswith(".docx"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f} this is my location from docx")

编辑:

我可以用下面的代码打印我想要的文件名,但是我不知道如何将该文件复制到一个新目录并使用它的目录路径位置重命名。

import os
import shutil as sh
from pathlib import Path

for root, dirs, files in os.walk(r'/Users/codychandler/SyncDrive/Colocation Information (Kory.Williams@charter.com )'):
for f in files:
if f.endswith(".pdf"):
print(os.path.abspath(os.path.join(root, f)))

试试这个:

import os
import shutil as sh
from pathlib import Path

root_path = Path("S:\Colocation Information (Kory.Williams@charter.com )")
dest_path = Path("C:\Users\P2187119\Documents\MSA_SO Crawl")

for root, _, fnames in os.walk(root_path):
for f in fnames:
source_file_path = Path(root, f)
ext = source_file_path.suffix
dest_file_path = Path(
dest_path, f"{source_file_path.stem}_{root_path.stem}{source_file_path.suffix}"
)
sh.copyfile(source_file_path, dest_file_path)

避免在代码中硬编码路径,这是一个非常坏的习惯,而是使用配置文件来存储它们,如json或yaml文件。此外,在脚本中输入路径时要注意如何使用反斜杠;我已经添加了一个双反斜杠,或者你可以使用一个单正斜杠。

然后,你的代码中有很多重复的行。

当你处理路径时,我建议你使用pathlib库,它将使路径的处理容易得多。

编辑

如果您希望复制的文件在其名称中包含根文件夹的完整路径,而不仅仅是根文件夹的名称,您可以像这样修改代码(有必要删除冒号和反斜杠字符):

import os
import shutil as sh
from pathlib import Path

root_path = Path("C:\Users\Blunova\Desktop\scripts\python\so\Colocation Information (Kory.Williams@charter.com )\")
dest_path = Path("C:\Users\Blunova\Desktop\scripts\python\so\P2187119\Documents\MSA_SO Crawl")

backslash_char = "\"
colon_char = ":"
for root, _, fnames in os.walk(root_path):
for f in fnames:
source_file_path = Path(root, f)
ext = source_file_path.suffix
dest_file_path = Path(
dest_path,
f"{source_file_path.stem}"
f"_{str(root_path.resolve()).replace(backslash_char, '_').replace(colon_char, '')}"
f"{source_file_path.suffix}"
)
sh.copyfile(source_file_path, dest_file_path)

例如,假设您有一个名为pdf_file.pdf的文件存储在您的root_path中(带有嵌套文件夹),该文件为:

C:\UsersBlunovaDesktopscriptspythonsoColocation Information (Kory.Williams@charter.com )

然后,如果您运行上面的代码,您将获得以下复制文件的名称(从根路径复制)在目标文件夹内):

pdf_file_C_Users_Blunova_Desktop_scripts_python_so_Colocation Information (Kory.Williams@charter.com ).pdf

最新更新