Loop over multiple folders from list with glob.glob

时间:2016-06-10 16:09:21

标签: python csv glob shutil

How can I loop over a defined list of folders and all of the individual files inside each of those folders?

I'm trying to have it copy all the months in each year folder. But when I run it nothing happens..

import shutil
import glob


P4_destdir = ('Z:/Source P4')

yearlist = ['2014','2015','2016']

for year in yearlist:
    for file in glob.glob(r'{0}/*.csv'.format(yearlist)):
        print (file)
        shutil.copy2(file,P4_destdir)

1 个答案:

答案 0 :(得分:1)

我认为问题可能是您在源路径中需要/

import shutil
import glob


P4_destdir = ('Z:/Source P4/')

yearlist = ['2014','2015','2016'] # assuming these files are in the same directory as your code.

for year in yearlist:
    for file in glob.glob(r'{0}/*.csv'.format(yearlist)):
        print (file)
        shutil.copy2(file,P4_destdir)

可能存在问题的另一个问题是目标文件是否尚不存在。您可以使用os.mkdir

创建它
import os

dest = os.path.isdir('Z:/Source P4/') # Tests if file exists
if not dest:
    os.mkdir('Z:/Source P4/')
相关问题