-2

There is a list named 'links' and I want to write as many files as the number of links inside this list (I'm doing web scraping). For example if the list contains 100 links, I would like to write data of each link to a separate text file like '1.txt','2.txt','3.txt'.... .

How can I achieve this type of auto file naming in python?

Talha Yousuf
  • 301
  • 2
  • 12

2 Answers2

3
for l, link in enumerate(links):
    filename = str(l+1)+".txt"
    #open file and write link contents to it

enumerate gives you the index, value pair from a list, and you can just use the index number as the filename

Imtinan Azhar
  • 1,725
  • 10
  • 26
1

You could use a for loop..

for i in range(1, 101): # since you started at 1 in your question
    fname='{}.txt'.format(i)
    with open(fname, 'wb') as f:
        f.write(data) # write your data to the file..
        f.close()
prince.e
  • 236
  • 2
  • 4