How to read a file Python code example.
Python make txt file and write to it, open it and catch any errors
‘r‘ open for reading (default)
‘w‘ open for writing, truncating the file first
‘x‘ open for exclusive creation, failing if the file already exists
‘a‘ open for writing, appending to the end of the file if it exists
# read, write, close a file # catch error if raise try: file = open("TryCatchFile.txt","w") file.write("Hello World") file = open("TryCatchFile.txt", "r") print(file.read()) except Exception as e: print(e) finally: file.close()