m-teng/m_teng/utility/file_io.py

34 lines
912 B
Python
Raw Permalink Normal View History

2023-04-06 22:55:24 +02:00
from os import listdir, path
2023-04-07 18:14:15 +02:00
def add_zeros(v: int, digits=3):
"""
return v as string, add leading zeros if len(str(v)) < digits
"""
s = str(v)
return '0' * (max(digits - len(s), 0)) + s
2023-04-06 22:55:24 +02:00
def get_next_filename(basename, directory=".", digits=3):
2023-04-07 18:14:15 +02:00
"""
get the next filename (without extenstion).
example:
basename = file
2023-04-13 11:09:40 +02:00
directory has file001.csv, file002.pkl, file004.csv
2023-04-07 18:14:15 +02:00
-> return file005
"""
2023-04-06 22:55:24 +02:00
files = listdir(directory)
files.sort()
files.reverse()
2023-04-13 11:09:40 +02:00
lowest_number = -1
2023-04-06 22:55:24 +02:00
for file in files:
if not file.startswith(basename): continue
try:
2023-04-27 01:40:56 +02:00
number = file[:file.rfind('.')].replace(basename, "")
number = int(number)
2023-04-06 22:55:24 +02:00
if number < lowest_number: continue
2023-04-07 18:14:15 +02:00
lowest_number = number
2023-04-06 22:55:24 +02:00
except ValueError:
continue
2023-04-13 11:09:40 +02:00
return basename + add_zeros(lowest_number+1)