如何使用python复制文件以及目录结构/路径? [英] How to copy a file along with directory structure/path using python?
本文介绍了如何使用python复制文件以及目录结构/路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先要在这里提到的是python,这是我的新手。
First thing I have to mention here, I'm new to python.
现在我有一个文件位于:
Now I have a file located in:
a/long/long/path/to/file.py
我想使用创建的新文件夹复制到我的主目录:
I want to copy to my home directory with a new folder created:
/home/myhome/new_folder
我的预期结果是:
/home/myhome/new_folder/a/long/long/path/to/file.py
是否有任何现有的库可以做到这一点?如果没有,我该如何实现?
Is there any existing library to do that? If no, how can I achieve that?
推荐答案
要创建所有中级目标目录,可以使用 os.makedirs()
:
To create all intermediate-level destination directories you could use os.makedirs()
before copying:
import os
import shutil
srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'
assert not os.path.isabs(srcfile)
dstdir = os.path.join(dstroot, os.path.dirname(srcfile))
os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
这篇关于如何使用python复制文件以及目录结构/路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文