[英]Copying files from one directory, and sub-directories, to another, so long as sub-directory names match
I'm fairly new working in python, I'm making the change from Excel to python, so my reference points tend to be in excel. 我是使用python的新手,我正在从Excel更改为python,因此我的参考点通常是excel。 I'm working out of python 2.7.
我正在使用python 2.7。 I understand how to copy files, and how to iterate through a folder copying all the files I need to a specific destination.
我了解如何复制文件,以及如何遍历文件夹将我需要的所有文件复制到特定目标。 What I am trying to do, however is a bit more complicated.
但是,我正在尝试做的事情比较复杂。
Here's the setup: 2 directories: 2017 and 2018 300+ folders in both 设置如下:2个目录:2017年和2018年300个文件夹
What I'm trying to do: Copy the files (shapefiles, .csv, etc.) from the individual folder in the directory 2017 to the folder of the same name (IF it exists, it may not, and that's okay) in the directory 2018. 我想做的是:将文件(shapefile,.csv等)从目录2017中的单个文件夹复制到相同名称的文件夹(如果存在,可能不存在,那没关系)。目录2018。
I know I need a for loop, and an if statement, I just don't know how to write it: If folder 'x' exists in both directories 2017 and 2018, copy files 'y_2017' from folder 'x' in 2017 to folder 'x' in 2018. 我知道我需要一个for循环和一个if语句,我只是不知道如何编写它:如果文件夹“ x”同时存在于目录2017和2018中,请将文件“ y_2017”从2017年的文件夹“ x”复制到文件夹'x'在2018。
I'm sure I described this in a poor manner and a rather convoluted way. 我敢肯定我以一种糟糕的方式和相当复杂的方式描述了这一点。 If anyone has any advice, I'd be appreciative.
如果有人有任何建议,我将不胜感激。
import os
import shutil
source_folder = "2017"
target_folder = "2018"
subfolders = [a for a in os.listdir(source_folder) if os.path.isdir(os.path.join(source_folder, a))]
for subfolder in subfolders:
if os.path.exists(os.path.join(target_folder, subfolder) and os.path.isdir(os.path.join(target_folder, subfolder)):
file_names = os.listdir(os.path.join(source_folder, subfolder))
for f in file_names:
src_path = os.path.join(source_folder, subfolder, f)
tgt_path = os.path.join(target_folder, subfolder, f)
shutil.copy(src_path, tgt_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.