[英]rename strings / rename files in python
I have a bunch of files like below: 我有一堆如下文件:
_1 blank file_
_10 - blank file_
_11 - blank file_
_2 blank file_
_3 blank file_
I would like to print out the name with the numbers padded (2 characters) 我想打印出带有填充数字(2个字符)的名称
I have : 我有 :
PATH = "/Users/seth/python/test"
#
#
for (path, dirs, files) in os.walk(PATH):
for z in files:
filename = z.replace(" ","_").replace("-","").replace("__","_")
print filename
Desired Output: 所需输出:
_01_blank_file_ _01_blank_file_
_02_blank_file_ _02_blank_file_
_03_blank_file_ _03_blank_file_
_10_blank_file_ _10_blank_file_
_11_blank_file_ _11_blank_file_
You can use rjust
for that: 您可以为此使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.