3

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'
6
  • 2
    Pls add the arr object to your question. Commented Sep 29, 2018 at 16:47
  • @Kasrâmvd you mean like this? Commented Sep 29, 2018 at 16:53
  • No, we need to know what's inside that iterable. Show the content of arr or at least some samples. Commented Sep 29, 2018 at 16:55
  • @Kasrâmvd random sentences, but just with words. No numbers can be used in sentence. Commented Sep 29, 2018 at 16:59
  • I don't get how your code relates to the question, but it sounds like you need to use a format string: "{:03}_{}".format(23, "name") evaluates to "023_name" Commented Sep 29, 2018 at 17:02

2 Answers 2

2

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']
Sign up to request clarification or add additional context in comments.

Comments

0

You could use string formatting and zfill to achieve the 00x effect. 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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.