我有如下文件名:
PRJ25 Sample1 Siver_Output_Log_2020_11_10_13.csv
PRJ25 Sample1 Siver_Output_Log_2020_12_30_4_1.csv
PRJ25 Sample1 Siver_Output_Log_2021_1_8_4.csv
我想从这些文件名输出到year, month, day
。我尝试了下面的代码,但文件名不一致,所以我无法获得这些值,预期结果:
year : 2020 or 2021
month: 11 or 12 or 1
day: 10 or 30 or 8
我代码:
year = file_name[len(file_name) - 14:len(file_name) - 10]
month = file_name[len(file_name) - 9:len(file_name) - 8]
day = file_name[len(file_name) - 7:len(file_name) - 6]
试试这个:
files = [
"PRJ25 Sample1 Siver_Output_Log_2020_11_10_13.csv",
"PRJ25 Sample1 Siver_Output_Log_2020_12_30_4_1.csv",
"PRJ25 Sample1 Siver_Output_Log_2021_1_8_4.csv",
]
results = [f.split("Log_")[-1].rsplit("_")[:3] for f in files]
print(results)
for result in results:
year, month, day = result
print(year, month, day)
# do your stuff here
输出:
[['2020', '11', '10'], ['2020', '12', '30'], ['2021', '1', '8']]
2020 11 10
2020 12 30
2021 1 8
您可以使用split函数:
year = file_name.split('_')[3]
Split将字符串转换为由指定字符分隔的字符串列表。对于第4年,我检索。
你可以试试:
year, month, day, last_num = filename.split("_")[-4:]
last_num = last_num.split(".")[0]