I have html line with gallery:
<div class="col-lg-4 col-md-6 portfolio-item "> <div class="portfolio-wrap"> <img src="img/portfolio/1.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4><a href="#">TITLE</a></h4> <p>DESCRIPTION</p> <div> <a href="img/portfolio/1.jpg" data-lightbox="portfolio" data-title="DESCRIPTION" class="link-preview" title="Preview"><i class="ion ion-eye"></i></a> </div> </div> </div> </div>
I need to add 100 more photos in gallery witch are named from 1.jpg to 101.jpg and I do not want to copy paste them one by one, but id rather use python to make it for me. I have got something like this:
fin = open("gallery.html", "rt") fout = open("gallery2.html", "wt") for line in fin: fout.write(line.replace('1.jpg', '2.jpg')) fin.close() fout.close()
But I need to know how to tell Python, to copy our lines 101 times and rewrite every numbers sequentially – from 1 to 101?
Advertisement
Answer
You could use a for loop and create a new string in each loop with the next integer:
for i in range(101): n = i+1 for line in fin: fout.write(line.replace('1.jpg',f'{n}.jpg'))
The f'{n}.jpg'
syntax is a very nice way to include variables into a string. I’m not sure how to parse it into your new html file to save it correctly.
Its even possible to put expressions inside the brackets of the formatted string which results in even cleaner code:
for i in range(101): for line in fin: fout.write(line.replace('1.jpg',f'{i+1}.jpg'))
For more string formatting info check this link on formatting f-strings.