将001格式的数字添加到python

时间:2018-09-29 16:45:09

标签: python python-3.x format filenames

我将txt文件上传到数组,然后将数组上传到网站,该网站将文件下载到特定目录。文件名包含数组行的前十个字母。 问题:在文件名之前添加00n格式的数字。我在这里尝试了一些技巧,但没有如我所愿。 txt文件中有随机的句子,例如“狗吠”

def openFile():
with open('test0.txt','r') as f:
    content = f.read().splitlines()
    for line in content:
       line=line.strip()
       line=line.replace(' ','+')
       arr.append(line)
    return arr  

def openWeb()
 for line in arr:
    url="url"
    name = line.replace('+', '')[0:9]
    urllib.request.urlretrieve(url, "dir"+"_"+name+".mp3")

所以输出应该看起来像

'001_nameoffirst' 
'002_nameofsecond'

2 个答案:

答案 0 :(得分:1)

可以使用 enumerate zfill 完成此操作,也可以将参数start = 1 enumerate 结合使用>

l = ['nameoffirst', 'nameofsecond']
new_l = ['{}_'.format(str(idx).zfill(3))+ item for idx, item in enumerate(l, start = 1)]

扩展循环:

new_l = [] 
for idx, item in enumerate(l, start = 1):
    new_l.append('{}_'.format(str(idx).zfill(3)) + item)
['001_nameoffirst', '002_nameofsecond']

答案 1 :(得分:0)

您可以使用字符串格式和zfill来达到00x的效果。我不确定您的数据是什么,但这说明了我的观点:

names = ['nameoffirst', 'nameofsecond']
for i, name in enumerate(names):
    form = '{}_{}'.format(str(i).zfill(3), name)
    print(form)  # or do whatever you
    # need with 'form'