我有一个文件夹,其中包含许多这样命名的文件:
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中创建文件夹,例如HOPE-> bound-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)
如果您的格式有一定的可变性和/或目录中包含多个文件,而您需要忽略其中的一些文件,则regex是一个合理的选择。\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_
示例代码中包含的文件,则可以使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句