shutil.move(src, dst) 是我认为可以完成的工作,但是,根据 python 2 document :
shutil.move(src, dst) Recursively move a file or directory (src) to another location (dst).
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
这与我的情况有点不同,如下所示:
搬家前: https://snag.gy/JfbE6D.jpg
shutil.move(staging_folder, final_folder)
移动后:
这不是我想要的,我希望将 staging 文件夹中的所有内容移动到文件夹“final”下,我不需要“staging”文件夹本身。
如能提供帮助,将不胜感激。
谢谢。
最佳答案
您可以使用 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)
示例代码(Python 3.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']
关于python移动文件夹内容而不移动源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50361720/