While working with python we might need to save our output in a text file. Generally they come from loops which sometimes might be tricky to handle.
So this recipe is a short example on how to add for loop output to a text file. Let's get started.
To start, we have to first create an object of a text file using the open function. We have used 'w' which refers to write function. Now df object stores the text file and can be easily written upon.
df.write('We will be seeing an interated printing of numbers between 0 to 10\n')
We have added a test line using write function.
for i in range(0,11): df.write(str(i)) df.write('\n')
We have created a loop, iterating over i from 0 to 10. Write function only accepts string values, hence converted the same using str function and finally adding a new line using '\n'
After all the amendments are done, use close fuction to simply close the file created.
Once we run the above code snippet, we will not be seeing any output. However, a file named test file would have been created in the directory you are working on, containing all your inputs.