Computer >> Computer tutorials >  >> Programming >> Python

How to open a file just to read in python?


To open files in read mode, specify 'r' as the mode. For example,

f = open('my_file.txt', 'r')
file_content = f.read()
f.close()

Above code opens my_file.txt in read mode and stores the file content in file_content variable. A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:

with open('my_file.txt', 'r') as f:
    print(f.read())