【发布时间】:2021-08-13 06:14:42
【问题描述】:
我写了如下函数:
def separate_files(filetree_list, destination):
from shutil import copyfile
from os import makedirs
from os.path import join, exists, commonprefix
try:
for file in filetree_list:
dst = join(destination,
'\\'.join(file.split(commonprefix(filetree_list))[1].split('\\')[0:-1]))
if not exists(dst):
print(dst, " doesn`t exist. Creating...")
makedirs(dst)
print(exists(dst), ". Path created.")
print(file)
copyfile(file, dst)
except:
print("Moving files has FAILED.")
else:
print("Moving files was SUCCESSFUL.")
当我使用“filetree_list”列表调用它时,该列表包含使用 os.path.join 准备的单个元素和目标:
filetree_list = ['C:\\Users\\<username>\\staging_folder\\folder_1\\filename.xlsx']
destination = os.path.join(staging_dir, 'Sorted', 'Unwanted_files')
我收到以下错误:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-29-c3525a60c859> in <module>()
14 print(exists(dst), ". Path created.")
15 print(file)
---> 16 copyfile(file, dst)
C:\ProgramData\Anaconda3\lib\shutil.py in copyfile(src, dst, follow_symlinks)
119 else:
120 with open(src, 'rb') as fsrc:
--> 121 with open(dst, 'wb') as fdst:
122 copyfileobj(fsrc, fdst)
123 return dst
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\<username>\\staging_folder\\Sorted\\Unwanted_files\\'
它有什么奇怪的(现在让我发疯),这个文件夹确实存在,并且是由单独文件函数中的“如果不存在(dst)”块创建的 - 我什至可以看到它在 Windows 资源管理器中!
雪上加霜的是,当我使用相同的目标参数但列表中有多个字符串运行此函数时,它会执行我的预期并且没有错误!
谁能提供任何关于我在这里做错了什么的见解?
【问题讨论】:
-
糟糕,抱歉 - 函数原型设计阶段的遗留问题。显然,它应该是 copyfile(file, dst) ,而不是 copyfile(file, join(destination, file.split(commonprefix(filetree_list))[1])) 之一。我现在将编辑该更改。
-
也更新了循环问题 - 对不起,我责怪我从 IDE 技能中复制不当。
-
dst是文件夹名称。with open(dst, 'wb')正在尝试将其作为文件打开(用于写入)。那是行不通的。 -
嗯,但目标参数不应该是文件夹,而不是文件吗? source 指向一个文件,而 dst 指向这个文件应该存放的文件夹?
标签: python file-transfer shutil