【Python】如何将文件名批量命名为四位数or五位数

for i in range(99):
    change_i = str(i).zfill(4)
    print(change_i)
    
"""输出为:
0000
0001
0002
0003
...
0098
"""



for i in range(99):
    change_i = str(i).zfill(5)
    print(change_i)

"""输出为:
00000
00001
00002
00003
...
00098
"""

问题来源:

本来想使用sorted(os.listdir(parh))按文件名顺序读取文件的,但是由于命名不没有统一,所以读出来没有按照预期来

接下来将文件名的数字部分统一命名为四位数的

import os
path = "/data/cta/deal-with-dataset-b-v1/dicom_hessian"

for file in os.listdir(path):
    num = file.split(".")[0].split("_")[-1]
    filename_change = "dicom_hessian_" + num.zfill(4) + ".jpg"
    os.rename(os.path.join(path, file), os.path.join(path, filename_change))

至此问题解决~

猜你喜欢

转载自blog.csdn.net/sinat_21791203/article/details/110424735