简体   繁体   English

Python:迭代移动文件夹

[英]Python: Iterating moving Folders

I have over 52k files of csv files that I need to organize and would like to find an efficient way to do this through python or some other avenue. 我需要整理超过52k的csv文件,并希望找到一种有效的方法来通过python或其他途径来做到这一点。

Currently I have these folders, 目前我有这些文件夹,

2013_Q1 2013_Q1
2013_Q2 2013_Q2
2013_Q3 2013_Q3
2013_Q4 2013_Q4
2014_Q1 ... 2014_Q1 ...

and so on 等等

Within the Quarter folder, i have another folder: 在Quarter文件夹中,我还有另一个文件夹:

xxxx20130101_000500_csv xxxx20130101_000500_csv
xxxx20130101_000500_xml xxxx20130101_000500_xml
xxxx20130101_001000_csv xxxx20130101_001000_csv
xxxx20130101_001000_xml xxxx20130101_001000_xml

and so on.. 等等..

within that folder I have the files: 在该文件夹中,我有以下文件:

xxxx20130101_000500_csv.csv xxxx20130101_000500_csv.csv
xxxx20130101_000500_xml.xml xxxx20130101_000500_xml.xml
xxxx20130101_001000_csv.csv xxxx20130101_001000_csv.csv
xxxx20130101_001000_xml.xml xxxx20130101_001000_xml.xml

respectively. 分别。

I want to go through all the quarter folders and extract only the .csv files from each sub-folder and organize them in a folder by their respective dates. 我想浏览所有季度文件夹,并从每个子文件夹中仅提取.csv文件,并按其各自的日期将它们组织在一个文件夹中。

So within the 2013_Q1 folder, I would like to have 因此,在2013_Q1文件夹中,我想拥有

20130101 20130101
20130102... 20130102 ...

and so on 等等

And within that 20130101 folder would be 在该20130101文件夹中

xxxx20130101_000500_csv.csv xxxx20130101_000500_csv.csv
xxxx20130101_001000_csv.csv xxxx20130101_001000_csv.csv
xxxx20130101_001500_csv.csv xxxx20130101_001500_csv.csv

Right now I have the python code: 现在我有python代码:

import shutil
import os

os.chdir('C:\\...\\Test')

 for f in os.listdir('MovingFolders'):
    folderName = f[-19:-11]

    if not os.path.exists(folderName):
        os.mkdir(folderName)
        shutil.copy(os.path.join('MovingFolders', f), folderName)
    else:
        shutil.copy(os.path.join('MovingFolders', f), folderName)

I'm fairly new at python and is still learning, so I'm a bit confused. 我是python的新手,现在还在学习,所以有点困惑。

For Python 3.5 and above: 对于Python 3.5及更高版本:

There is a recursive feature in glob that you could use. 您可以使用glob中的一个递归功能。 Here's what you do import glob 这是您导入glob的操作

loop over glob.glob('root/**/*.csv',recursive = True) 遍历glob.glob('root / ** / *。csv',recursive = True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM