shutil.move(src,dst)是我认为将完成的工作,然而,根据python 2文档
shutil.move(src,dst)递归地将文件或目录(src)移动到另一个位置(dst)。 如果目标是一个现有目录,那么src将移到该目录中。如果目标已经存在但不是目录,则可能会根据os.rename()语义覆盖它。
这与我的情况有点不同,如下所示:
搬家前:https://snag.gy/JfbE6D.jpg
shutil.move(staging_folder, final_folder)搬家后:
这不是我想要的,我希望将暂存文件夹中的所有内容移到文件夹"final“下面,我不需要”暂存“文件夹本身。
如果你能帮忙的话,我们将不胜感激。
谢谢。
发布于 2018-05-19 12:38:52
事实证明,路径是不正确的,因为它包含被误解的\t。
最后我使用了shutil.move + shutil.copy22
for i in os.listdir(staging_folder):
if not os.path.exists(final_folder):
shutil.move(os.path.join(staging_folder, i), final_folder)
else:
shutil.copy2(os.path.join(staging_folder, i), final_folder)然后清空旧文件夹:
def emptify_staging(self, folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
# elif os.path.isdir(file_path): shutil.rmtree(file_path)
except Exception as e:
print(e)发布于 2021-07-24 12:16:50
您可以使用shutil.copytree()将staging_folder中的所有内容移动到final_folder中,而无需移动staging_folder。调用函数时传递参数copy_function=shutil.move。
对于Python 3.8:
shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)Python 3.7及以下版本:
注意,参数dirs_exist_ok不受支持。目标final_folder 不能已经存在,因为它将在移动过程中创建。
shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move)示例代码(Python3.8):
>>> os.listdir('staging_folder')
['file1', 'file2', 'file3']
>>> os.listdir('final_folder')
[]
>>> shutil.copytree('staging_folder', 'final_folder', copy_function=shutil.move, dirs_exist_ok=True)
'final_folder'
>>> os.listdir('staging_folder')
[]
>>> os.listdir('final_folder')
['file1', 'file2', 'file3']发布于 2018-05-16 02:48:19
您可以使用os.listdir,然后将每个文件移动到所需的目标。
Ex:
import shutil
import os
for i in os.listdir(staging_folder):
shutil.move(os.path.join(staging_folder, i), final_folder)https://stackoverflow.com/questions/50361720
复制相似问题