[英]Add number in 001 format to file name in python
I upload a txt file to array and then I upload the array to a website, that downloads a file to a specific directory.我将 txt 文件上传到数组,然后将数组上传到网站,该网站将文件下载到特定目录。 The file name contains first ten letters of a array line.文件名包含数组行的前十个字母。 Problem: add number in 00n format before the file name.问题:在文件名前添加00n格式的数字。 I tried several tips here but nothing works as I wished.我在这里尝试了几个技巧,但没有任何效果如我所愿。 In txt file are random sentences like "Dog is barking"在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")
so the output should look like所以输出应该看起来像
'001_nameoffirst'
'002_nameofsecond'
Using enumerate and zfill this can be done, also you can use the argument start = 1
in combination with enumerate使用enumerate和zfill可以做到这一点,也可以将参数start = 1
与enumerate结合使用
l = ['nameoffirst', 'nameofsecond']
new_l = ['{}_'.format(str(idx).zfill(3))+ item for idx, item in enumerate(l, start = 1)]
Expanded loop:扩展循环:
new_l = []
for idx, item in enumerate(l, start = 1):
new_l.append('{}_'.format(str(idx).zfill(3)) + item)
['001_nameoffirst', '002_nameofsecond']
You could use string formatting and zfill
to achieve the 00x
effect.您可以使用字符串格式和zfill
来实现00x
效果。 I'm not sure what your data is, but this illustrates my point:我不确定你的数据是什么,但这说明了我的观点:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.