如何使用python复制文件以及目录结构/路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12842997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:58:34  来源:igfitidea点击:

How to copy a file along with directory structure/path using python?

pythonfiledirectorycopy

提问by Js Lim

First thing I have to mention here, I'm new to python.

我必须在这里提到的第一件事,我是 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?

有没有现有的图书馆可以做到这一点?如果没有,我怎样才能做到这一点?

采纳答案by jfs

To create all intermediate-level destination directories you could use os.makedirs()before copying:

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)

回答by ewok

take a look at shutil. shutil.copyfile(src, dst)will copy a file to another file.

看看shutilshutil.copyfile(src, dst)将一个文件复制到另一个文件。

Note that shutil.copyfilewill not create directories that do not already exist. for that, use os.makedirs

请注意,shutil.copyfile不会创建尚不存在的目录。为此,使用os.makedirs