navajyothmp
navajyothmp

Reputation: 95

How to write multiple lines with a varying number in each line?

I've been trying to create a text file using python in which I must write around 200 lines. Each line contains the same string but it contains a number that ranges from 1901 to 2100. For example,

this_is_the_string_with_a_number_xxxx_in_each_line

where xxxx varies from 1901 to 2100 (in the ascending order itself). How do I write these lines to a txt file using python?

Upvotes: 0

Views: 78

Answers (1)

Ali Yılmaz
Ali Yılmaz

Reputation: 1695

this should do the work:

with open("my_file.txt", "w") as myfile:
   stub_string = "this_is_the_string_with_a_number_%s_in_each_line\n"
   for number in range(1901, 2100):
      string_with_number = stub_string % number
      myfile.write(string_with_number)

Upvotes: 2

Related Questions