Following example will populate the output.txt file with the squares of numbers from 1 - 10.
my_list = [i**2 for i in range(1,11)]
f = open(“output.txt”, “w”)
for item in my_list: f.write(str(item) + “\n”)
f.close()
You have probably noticed that we are opening the file in “w” mode, i.e. for writing. We can use “r+” flag if we would like to read and write from the file.
In this example, we are using with and as syntax. Using this statement python will execute the required operations on the file and will close it automatically:
with open(“output.txt”, “w”) as file: file.write(“File will be automatically closed!")
if not file.closed: print “Closing file …” file.close() else: print “Skipping file closing, it was closed for us!”
my_file = open(“output.txt”, “r”)
print my_file.readline()
print my_file.read()
my_file.close()