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

标签 python regex python-3.x

我有一个包含许多文件的文件夹,其名称如下:

sale_jone_BAL_EXT_HOPE_20191121130102.txt.xml.done 
sale_jone_BAL_EXT_HOPE_20191121131102.txt.xml.done
sale_jone_BAL_EXT_HOPE_20191122133102.txt.xml.done    
sale_jone_BAL_EXT_HOPE_20191123132102.txt.xml.done
sale_jone_BAL_EXT_LOCK_20191123132102.txt.xml.done
sale_jone_BAL_EXT_LOCK_20191123132102.txt.xml.done

我想根据上面给出的文件名创建名称为 (bound-2019-11-21) 的文件夹。在文件中,前 8 个整数是日期。

我怎样才能做到这一点? 这里我有一个文件夹 希望 锁定

现在我想要的是根据文件名在 HOPE 中创建文件夹 例如 希望-->绑定(bind)-2019-11-21

这是我的代码:

path='../picture/jack' #this is the path of folder in which the files are 
                        located
dirs=os.listdir(path)
b=[]
for file in dirs:
    #print(file)
    a=re.findall(r'HOPE',file) #finding the file name HOPE from the folder
    if a:
      b.append(file)

print(b)
for i in b:
    t=re.findall(r'\d{8}',i) #finding the date from the file in list
    print(t)

最佳答案

如果您的格式存在一些可变性和/或目录中存在混合文件(其中一些文件需要忽略),则正则表达式是一个合理的选择。 \w+?(\d{8,})\.txt\.xml\.done$ 似乎是一个很好的开始方法,因为我们只有单词字符,一批至少 8 位数字,并且.txt.xml.done 后缀。

import os
import re

path = "../picture/jack"
path = os.path.join(*path.split("/"))

for f in os.listdir(path):
    date = re.match(r"\w+?(\d{8,})\.txt\.xml\.done$", f)

    if date:
        p = r"(\d{4})(\d\d)(\d\d).*"
        dest = os.path.join(path, re.sub(p, r"\1-\2-\3", date.group(1)))
        os.makedirs(dest, exist_ok=True)
        os.replace(os.path.join(path, f), os.path.join(dest, f))

这将根据 yyyy-mm-dd 格式在文件夹中创建和移动文件。

您可以使用“\w*?_HOPE_\w*?(\d{8,})\.txt\.xml\.done$” 如果您只需要包含 _HOPE_ 的文件(如示例代码中所示)。

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

相关文章:

python - 如何添加一个计数器来跟踪 while 循环中的月份和年份?

python - 如何在循环中制作 tkinter 框架并更新对象值?

python - 将列名转换为数字?

python - 操作系统: programmatically get list of applications for a file

java - 如何检查邮箱验证?错误是什么?

regex - 如何从 url 中删除查询字符串?

python - Django 缓存 - Pickle 很慢

python - 神经网络模拟误差

python - 使用带有反向引用的Python匹配字符串中的对象

python - 在 PyQt5 中的图像顶部绘制跟踪鼠标