gpt4 book ai didi

python - 根据文件名创建文件夹

转载 作者:行者123 更新时间:2023-11-28 17:03:58 25 4
gpt4 key购买 nike

我有一个包含大约 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 没有固定长度,可以变化。

我想为每个唯一的日期创建文件夹(文件夹名称应该是日期)并将具有相同日期的文件移动到一个文件夹中。因此,对于上面的示例,必须创建 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 )...

关于python - 根据文件名创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52467516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com