Python-移动和覆盖文件和文件夹 [英] Python - Move and overwrite files and folders

查看:1538
本文介绍了Python-移动和覆盖文件和文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录"Dst Directory",其中包含文件和文件夹,而我有"src Directory",其中也包含文件和文件夹.我想要做的是将"src目录"的内容移动到"Dst目录",并覆盖具有相同名称的所有文件.因此,例如,需要将"Src Directory \ file.txt"移至"Dst Directory \"并覆盖现有的file.txt.对于某些文件夹,移动文件夹并将内容与"dst目录"中的同一文件夹合并,也是如此.

I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist with the same name. So for example 'Src Directory\file.txt' needs to be moved to 'Dst Directory\' and overwrite the existing file.txt. The same applies for some folders, moving a folder and merging the contents with the same folder in 'dst directory'

我当前正在使用shutil.move将src的内容移动到dst,但是如果文件已经存在并且不会合并文件夹,它将不会执行该操作;只需将文件夹放入现有文件夹中即可.

I'm currently using shutil.move to move the contents of src to dst but it won't do it if the files already exist and it won't merge folders; it'll just put the folder inside the existing folder.

更新:为了使事情更清楚,我正在做的是将存档解压缩到Dst目录,然后将Src目录的内容移到那里并重新压缩,从而有效地更新了zip存档中的文件.添加新文件或文件的新版本等将重复此操作,这就是为什么它需要覆盖和合并

Update: To make things a bit clearer, what I'm doing is unzipping an archive to the Dst Directory and then moving the contents of Src Directory there and rezipping, effectively updating files in the zip archive. This will be repeated for adding new files or new versions of files etc which is why it needs to overwrite and merge

已解决:我通过使用distutils.dir_util.copy_tree(src,dst)解决了我的问题,这将文件夹和文件从src目录复制到dst目录,并在需要时覆盖/合并.希望对某些人有所帮助!

Solved: I solved my problem by using distutils.dir_util.copy_tree(src, dst), this copies the folders and files from src directory to dst directory and overwrites/merges where neccesary. Hope that helps some people!

希望如此, 谢谢!

推荐答案

请改用copy(),它愿意覆盖目标文件.如果您随后希望第一棵树消失,则在对其进行遍历之后,只需分别rmtree()对其进行遍历.

Use copy() instead, which is willing to overwrite destination files. If you then want the first tree to go away, just rmtree() it separately once you are done iterating over it.

http://docs.python.org/library/shutil.html#shutil.copy

http://docs.python.org/library/shutil.html#shutil.rmtree

更新:

在源树上执行os.walk().对于每个目录,请检查目标目录中是否存在该目录,如果缺少目录,请os.makedirs().对于每个文件,只需shutil.copy(),然后将创建或覆盖该文件,以适当的方式为准.

Do an os.walk() over the source tree. For each directory, check if it exists on the destination side, and os.makedirs() it if it is missing. For each file, simply shutil.copy() and the file will be created or overwritten, whichever is appropriate.

这篇关于Python-移动和覆盖文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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