Python - Read and write file

By xngo on June 5, 2019

#!/usr/bin/python3
# Description: Read and write file using Python.
 
# open() mode options:
#   r = open for reading.
#   a = append to the end of the file.
#   x = create a file, returns an error if the file exist.
#   w = overwrite any existing content.
 
 
# Write
# ##########
file = open("my-file.txt", "a")
 
# Add text to file.
file.write("First line.\n")
file.write("Second line.\n")
file.write("Third line.\n")
 
# Close file.
file.close()
 
# Read
# ##########
file = open("my-file.txt", "r")
print(file.read()) # Read the whole file.
 
# Read each line.
with open("my-file.txt", "r") as file:
    for line in file.readlines():
        print(line)
 
# Note: Using 'with' statement will automatically close the file after your are done.
#           There is no need to explicitly close the file.

Read and write file result

Reference:

  • https://docs.python.org/3/library/functions.html#open
  • http://docs.python.org/reference/compound_stmts.html#the-with-statement

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.