Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The file name contains first ten letters of a array line. Problem: add number in 00n format before the file name. I tried several tips here but nothing works as I wished. In txt file are random sentences like "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")

so the output should look like

'001_nameoffirst' 
'002_nameofsecond'
like image 289
carolinesed Avatar asked Dec 31 '25 21:12

carolinesed


1 Answers

Using enumerate and zfill this can be done, also you can use the argument start = 1 in combination with 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']
like image 147
vash_the_stampede Avatar answered Jan 03 '26 11:01

vash_the_stampede



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!