在 python 中的文件名中添加 001 格式的数字

Add number in 001 format to file name in python

我将一个 txt 文件上传到数组,然后将该数组上传到一个网站,该网站将文件下载到特定目录。文件名包含数组行的前十个字母。 问题:在文件名前添加 00n 格式的数字。我在这里尝试了几个技巧,但没有任何效果如我所愿。 在 txt 文件中是随机的句子,例如 "Dog is barking"

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'

您可以使用字符串格式和 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'

使用 enumeratezfill 可以做到这一点,您也可以将参数 start = 1 与 [= 结合使用19=]枚举

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']