Home  »  CodeLibrariesProgrammingSnippetsTechnology   »   How to Read a File in Python

How to Read a File in Python

Posted: March 16, 2022 | by Michael Bright

How to read a file Python code example.

Python make txt file and write to it, open it and catch any errors

Key:

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()

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.