如何使用python复制文件? [英] How to copy a file using python?

查看:126
本文介绍了如何使用python复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



现在我有一个文件位于:


$

b $ b

  a / long / long / path / to / file.py 

我要复制到我的主目录并创建一个新文件夹:

  / home / myhome / new_folder 

我的预期结果是:

  /home/myhome/new_folder/a/long/long/path/to/file.py 

有没有现成的库来做呢?

要创建所有中间级目标目录,您可以使用 http://docs.python.org/library/os#os.makedirs> 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)#创建所有目录,如果已经存在则产生一个错误
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆