【问题标题】:Loop over multiple folders from list with glob.glob使用 glob.glob 遍历列表中的多个文件夹
【发布时间】:2016-06-10 16:09:21
【问题描述】:

如何遍历已定义的文件夹列表以及每个文件夹中的所有单个文件?

我试图让它复制每年文件夹中的所有月份。但是当我运行它时没有任何反应..

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)

【问题讨论】:

  • 您可以为此使用os.walk()
  • 您在哪个目录运行您的脚本?该目录中是否存在目录201420152016?如果没有,请将它们指定为绝对路径。

标签: python csv glob shutil


【解决方案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/')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    相关资源
    最近更新 更多