如何使用python复制文件? [英] How to copy a file using python?
本文介绍了如何使用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()
: / p>
import os
import shutil
srcfile ='a / long / long / path /到/ 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)#创建所有目录,如果已经存在,引发错误
shutil.copy(srcfile ,dstdir)
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
My expected result is:
/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?
解决方案
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屋!
查看全文