根据文件名创建文件夹

Create folders based on filenames

我有一个包含大约 1500 个 excel 文件的文件夹。每个文件的格式是这样的:

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

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

我想知道在python中有没有办法做到这一点?抱歉没有发布任何示例代码,因为我不知道如何开始。

试试这个:

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+-]+)(您可以使用它并查看有关如何阅读它的详细信息here)...

检查此代码。

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

试试这个:

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)