[Python]: File Input / Output

Writing to file

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)]
# Generates a list of squares of the numbers 1 - 10

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!"

Reading from file

my_file = open("output.txt", "r")

# will output the contents of a single line while the pointer is and 
# moves the pointer to the next line
# output: one line contents
print my_file.readline()

# output: the contents of output.txt file from the pointer location to
# the end of file - will move the pointer to the end of file
print my_file.read()

my_file.close()

 

Majd Arbash

...

Leave a Reply