Skip to content

I need to write the output to a file and the file needs to look exactly like the output

import time

while True:
  for x in range(1, 1000, 1) :
    link = ("" + str(x))  

Here is the code, I need the link variable to be written to a file like

and so on

The problem i ran into before posting this is that when I write something to a file ( in the next cycle the text gets replaced by the new output ( Is there a way for me to write to the file in such a way that the script wouldnt replace the already existing lines and start from a new one every cycle

P.S this is my first post and im new to python, pls dont attack me if I did anything wrong!


There are a few ways you could go about this.

Depending on your environment, you can likely redirect your output to a file: > out.txt

Would output what you print() to out.txt (instead of the screen).

This tutorial will help you with writing (and reading in python).

To write to a file in python, you need to get a handle to the file using open:

writer = open('dog_breeds.txt', 'w')

(the ‘w’ means open for writing, it will overwrite any existing contents).

Once, you have the handle, you can write() to it, which is very similar to print():

writer.write("" + str(x))  

Lastly, you need to close the file:


You should be able to modify your existing snippet to make use of the above, and refer to the link to go a bit deeper (including error checking).