使用 python 根据包含日期的文件名创建文件夹和子文件夹
create folder and subfolder based on filename that contain the date using python
我有多个包含日期的文件。例如文件名是:
one08172021patient.txt
two09182021patient.txt
three09182021patient.txt
我想在 python 中编写一个脚本来为年、月、日创建文件夹,并根据文件名中已有的日期移动文件。
我在 google 中四处寻找这个逻辑,但我没有找到。本案例的结果。
在 运行 代码之后,结果将类似于:
+---2021
| \---08
| ----17 one08172021patient.txt
|
\---2021
+---09
------18
two09182021patient.txt
这可以通过 re 模块使用正则表达式简单地完成,例如:
import re
data= ["one08172021patient.txt","two09182021patient.txt","three09182021patient.txt"]
for file in data:
date = re.match(r"^\D+(\d{2})(\d{2})(\d{4})patient.txt",file)
month = date[1]
day = date[2]
year = date[3];
print(month,day,year)
# Your code to save file
if __name__ == "__main__":
pass
这将给出以下输出
08 17 2021
09 18 2021
09 18 2021
您可以使用这个脚本:
import re
from os import walk, rename
from pathlib import Path
src_path = './src'
des_path = './dst'
filenames = next(walk(src_path), (None, None, []))[2]
for file in filenames:
match = re.search(r'^\D+(\d{2})(\d{2})(\d{4})', file)
if match:
month = match.group(1)
day = match.group(2)
year = match.group(3)
path = f'{des_path}/{year}/{month}/{day}'
Path(path).mkdir(parents=True, exist_ok=True)
rename(f'{src_path}/{file}', f'{path}/{file}')
我有多个包含日期的文件。例如文件名是:
one08172021patient.txt
two09182021patient.txt
three09182021patient.txt
我想在 python 中编写一个脚本来为年、月、日创建文件夹,并根据文件名中已有的日期移动文件。 我在 google 中四处寻找这个逻辑,但我没有找到。本案例的结果。
在 运行 代码之后,结果将类似于:
+---2021
| \---08
| ----17 one08172021patient.txt
|
\---2021
+---09
------18
two09182021patient.txt
这可以通过 re 模块使用正则表达式简单地完成,例如:
import re
data= ["one08172021patient.txt","two09182021patient.txt","three09182021patient.txt"]
for file in data:
date = re.match(r"^\D+(\d{2})(\d{2})(\d{4})patient.txt",file)
month = date[1]
day = date[2]
year = date[3];
print(month,day,year)
# Your code to save file
if __name__ == "__main__":
pass
这将给出以下输出
08 17 2021
09 18 2021
09 18 2021
您可以使用这个脚本:
import re
from os import walk, rename
from pathlib import Path
src_path = './src'
des_path = './dst'
filenames = next(walk(src_path), (None, None, []))[2]
for file in filenames:
match = re.search(r'^\D+(\d{2})(\d{2})(\d{4})', file)
if match:
month = match.group(1)
day = match.group(2)
year = match.group(3)
path = f'{des_path}/{year}/{month}/{day}'
Path(path).mkdir(parents=True, exist_ok=True)
rename(f'{src_path}/{file}', f'{path}/{file}')