我正在使用python每天创建一次或两次文件夹,我需要从上次创建文件夹时开始按顺序使用PART的名称。
ie:180208_001
(date_sequence)。
我将日期部分缩小了,但现在我需要查看最后一个数字和序列:
180208_001
180208_002
180209_003
etc...
答案 0 :(得分:1)
您可以按" _"拆分文件夹名称。递增它然后使用zfill方法获得所需的输出。
<强>实施例强>:
a = "180208_001"
a = a.split("_")[-1]
print str(int(a) + 1).zfill(len(a))
<强>输出:强>
002
答案 1 :(得分:0)
# string spliting
v = "180208_001"
# spliting v into date and sequence number.
print(v.split('_'))
# ['180208', '001']
d = v.split('_')[0] # first element of list '180208'
print(d)
s = v.split('_')[1] # second element of list '001'
print(s)
# now taking the last part from sequence
print(s[-1])
答案 2 :(得分:0)
In [23]: date = "180208"
In [24]: ls
180208_001/ 180208_002/ 180209_003/
In [25]: numbers = [int(str(dir_name).split("_")[1]) for dir_name in current_path.iterdir() if current_path.is_dir()]
In [26]: max_number = max(numbers)
In [27]: new_name = "180208_{}".format(str(max_number + 1).zfill(3))
In [28]: new_name
Out[28]: '180208_004'
首先获取所有目录,然后拆分以找到最大数字,然后按最大数字加1创建一个新名称。
答案 3 :(得分:0)
此函数将分析给定目录的子目录,并从其中返回递增的字符串:
import os
def toIntOrNone(nr:str):
try:
return int(nr)
except:
return None
def getIncName(dirr:str, name:str, lenNr=3):
"""Returns the incremented max value of a named subdir structured
like name+'_'+number or returns name+'_'+ 1 padded with 0 to lenNr"""
if not name:
raise ValueError("name can not be empty")
highestNr = 0
# read all subdirs that match ...._...
for f in [f.path for f in os.scandir(dirr) if f.is_dir()]:
splitted = f.split('_')
if len(splitted) == 2:
key = splitted[0].split("\\")[-1]
value = toIntOrNone(splitted[1])
if key == name and value:
highestNr = max(highestNr, value)
# return incremented one
return name + "_" + str(highestNr + 1).zfill(lenNr)
print(getIncName('.',"test",5))
print(getIncName('.',"180918",5))
print(getIncName('.',None,5))
在包含180918_003
,180918_005
和180918_15tata
的词典中:
test_00001
180918_00006
Traceback (most recent call last):
File "my.py",
print( getIncName('.',None,5 ))
File my.py", in getIncName
raise ValueError("name can not be empty")
ValueError: name can not be empty