Python, read file content

To read the contents of the file, you first need to useopen()Global function, it accepts 2 parameters: file path andmode.

To read, use the read (r) Mode:

filename = '/Users/flavio/test.txt'

file = open(filename, ‘r’)

#or

file = open(filename, mode=‘r’)

After opening the file, you can useread()The method to read the entire contents of the file into a string:

content = file.read()

You can also choose to read the content one line at a time:

line = file.readline()

This is usually used in conjunction with loops, such as reading each line into a list item:

filename = '/Users/flavio/test.txt'

file = open(filename, ‘r’)

while True: line = file.readline() if line == ‘’: break print(line)

At the end of file processing, remember to close the file:

file.close()

More python tutorials: