0

我有一堆文件,如下所示:

_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_空白文件_

_02_空白文件_

_03_空白文件_

_10_blank_file_

_11_blank_file_

4

1 回答 1

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)
于 2012-01-14T22:07:48.087 回答