Skip to main content

Reading Files

Here is how to open and read a file's content:

# open(file_path, mode)
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file to free up system resources

Using the with keyword is safer because Python automatically closes the file for you, even if an error happens.

with open("sample.txt", "r") as file:
content = file.read()
print(content)