根据文件名创建文件夹

时间:2018-09-23 15:20:20

标签: python file iteration directory batch-processing

我有一个包含1500个excel文件的文件夹。每个文件的格式如下:

  • 0d20170101abcd.xlsx
  • 1d20170101ef.xlsx
  • 0d20170104g.xlsx
  • 0d20170109hijkl.xlsx
  • 1d20170109mno.xlsx
  • 0d20170110pqr.xlsx

文件名的第一个字符为'0'或'1',后跟'd',后跟创建文件的日期,后跟客户id(abcd,ef,g,hijkl,mno,pqr) 。客户ID没有固定的长度,并且可以变化。

我想为每个唯一的日期(文件夹名称应为date)创建文件夹,并将具有相同日期的文件移动到单个文件夹中。 因此,对于上面的示例,必须创建4个文件夹(20170101,20170104,20170109,20170110),并将具有相同日期的文件复制到各自的文件夹中。

我想知道在 python 中是否可以执行此操作?很抱歉没有发布任何示例代码,因为我不知道如何开始。

3 个答案:

答案 0 :(得分:2)

尝试一下:

import os
import re

root_path = 'test'


def main():
    # Keep track of directories already created
    created_dirs = []

    # Go through all stuff in the directory
    file_names = os.listdir(root_path)
    for file_name in file_names:
        process_file(file_name, created_dirs)


def process_file(file_name, created_dirs):
    file_path = os.path.join(root_path, file_name)

    # Check if it's not itself a directory - safe guard
    if os.path.isfile(file_path):
        file_date, user_id, file_ext = get_file_info(file_name)

        # Check we could parse the infos of the file
        if file_date is not None \
            and user_id is not None \
            and file_ext is not None:
            # Make sure we haven't already created the directory
            if file_date not in created_dirs:
                create_dir(file_date)
                created_dirs.append(file_date)

            # Move the file and rename it
            os.rename(
                file_path,
                os.path.join(root_path, file_date, '{}.{}'.format(user_id, file_ext)))

            print file_date, user_id


def create_dir(dir_name):
    dir_path = os.path.join(root_path, dir_name)
    if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
        os.mkdir(dir_path)


def get_file_info(file_name):
    match = re.search(r'[01]d(\d{8})([\w+-]+)\.(\w+)', file_name)
    if match:
        return match.group(1), match.group(2), match.group(3)

    return None, None, None


if __name__ == '__main__':
    main()

请注意,根据文件名的不同,您可能希望(以后)更改我使用的正则表达式,即[01]d(\d{8})([\w+-]+)(可以使用它,并查看有关如何阅读它的详细信息{{ 3}})...

答案 1 :(得分:0)

检查此代码。

import os

files = list(x for x in os.listdir('.') if x.is_file())

for i in files:
  d = i[2:10] #get data from filename
  n = i[10:] #get new filename
  if os.path.isdir(i[2:10]):
    os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)
  else:
    os.mkdir(os.getcwd()+i)
    os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)

这里是代表link

答案 2 :(得分:0)

尝试一下:

import os, shutil
filepath = "your_file_path"
files = list(x for x in os.listdir(filepath) if x.endswith(".xlsx"))
dates = list(set(x[2:10] for x in files))
for j in dates:
    os.makedirs(filepath + j)
for i in files:
    cid = i[10:]
    for j in dates:
        if j in i:
            os.rename(filepath+i,cid)
            shutil.copy2(filepath+cid, filepath+j)
相关问题