在python中重命名字符串/重命名文件

时间:2012-01-14 21:36:12

标签: python string alphanumeric pad

我有一堆如下文件:

_1 blank file_
_10 - blank file_
_11 - blank file_
_2 blank file_
_3 blank file_

我想用填充的数字打印出这个名字(2个字符)

我有:

PATH = "/Users/seth/python/test"
#
#
for (path, dirs, files) in os.walk(PATH):

    for z in  files:

        filename = z.replace(" ","_").replace("-","").replace("__","_")
        print filename

期望输出:

_01_blank_file _

_02_blank_file _

_03_blank_file _

_10_blank_file _

_11_blank_file _

1 个答案:

答案 0 :(得分:1)

您可以使用rjust

for (path, dirs, files) in os.walk(PATH):
  for z in files:
    filename = z.replace(" ","_").replace("-","").replace("__","_")

    # explode and transform number
    parts = filename.split('_', 2)
    parts[1] = parts[1].rjust(2, '0')

    # rejoin the transformed parts
    print '_'.join(parts)