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


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
    file = open("TryCatchFile.txt","w") 
    file.write("Hello World")

    file = open("TryCatchFile.txt", "r")
except Exception as e:

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