Python

File handling

Read a file

file = open("my_file.txt", "rt")  # default flags, see below
print(file.read())
file.close()

Using a context manager -> auto-closes file

with open("my_file.txt", 'r') as file:
    for line in file:
        print(line)

Write to a file

file = open("my_file.txt", "w")
file.write("my text"), 
file.close()

# using a context manager => auto-closes file
with open("my_file.txt", 'w') as file:
    file.write("my text")

Action flags

  • "r" Read - Default value. Opens a file for reading, error if the file does not exist
  • "a" Append - Opens a file for appending, creates the file if it does not exist
  • "w" Write - Opens a file for writing, creates the file if it does not exist
  • "x" Create - Creates the specified file, returns an error if the file exists

Mode flags

  • "t" Text - Default value. Text mode
  • "b" Binary - Binary mode (e.g. images)