首先要说明的是,我是Python的新手。
现在我有一个文件位于:
a/long/long/path/to/file.py
我想将文件复制到我的主目录,并创建一个新的文件夹:
/home/myhome/new_folder
我的期望结果是:
/home/myhome/new_folder/a/long/long/path/to/file.py
有没有现成的库可以做到这一点?如果没有,我该如何实现?首先要说明的是,我是Python的新手。
现在我有一个文件位于:
a/long/long/path/to/file.py
我想将文件复制到我的主目录,并创建一个新的文件夹:
/home/myhome/new_folder
我的期望结果是:
/home/myhome/new_folder/a/long/long/path/to/file.py
有没有现成的库可以做到这一点?如果没有,我该如何实现?在复制之前,您可以使用os.makedirs()
来创建所有中间目录:
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)
os.makedirs(dstdir)
dstfile = os.path.join(dst, src)
shutil.copyfile(src, dstfile)
- Js Limcopy()
函数支持将目录作为第二个参数进行复制(注意:copy()
与copyfile()
的区别)。 - jfsscrfile
更正为 srcfile
。 - Tanky Woo请查看shutil
。 shutil.copyfile(src, dst)
可将文件复制到另一个文件中。
请注意,shutil.copyfile
不会创建不存在的目录。如需创建,请使用os.makedirs
。