Reputation: 27
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?
Upvotes: 1
Views: 605
Reputation: 827
You could do something like this (I'm under the assumption what you want is to append multiple HTML elements with different links).
Use formatting, e.g use format code 0 and replace each it in them with every value in each iteration from 0 to 101 inclusive.
template = """
<div class="col-lg-4 col-md-6 portfolio-item ">
<div class="portfolio-wrap">
<img src="img/portfolio/{0}.jpg" class="img-fluid" alt="">
<div class="portfolio-info">
<h4><a href="#">TITLE</a></h4>
<p>DESCRIPTION</p>
<div>
<a href="img/portfolio/{0}.jpg" data-lightbox="portfolio" data-title="DESCRIPTION" class="link-preview" title="Preview"><i class="ion ion-eye"></i></a>
</div>
</div>
</div>
</div>
"""
html = ""
maximum = 101
# stop at 102
for i in range(maximum+1):
html += template.format(i)
print(html)
# now write this output to your file if you want
with open("gallery2.html", "w") as f:
f.write(html)
Note: since you're printing too much, Visual Studio Code (or at least by default in the terminal) will only output the string till 25. Use some other IDE or something to get the full output.
Upvotes: 2
Reputation: 130
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.
Upvotes: 0