Reading from a file

To read the data from an opened file handler you can use the read() function. This returns the contents of the file which you would normally assign to a variable.

with open("data.txt") as input_file:
    file_contents = input_file.read()

print(file_contents)

However, most files are large and storing all the data in a single variable will make it harder to process. To work around this, you can use either the splitlines() or readlines() functions, or by using a for loop. These break the file into individual lines by looking for newline characters within a file. As such they will not be useful for binary files.

with open("data.txt") as input_file:
    file_lines_array = input_file.read().splitlines()

    for line in file_lines_array:
        print(line)
with open("data.txt") as input_file:
    file_lines_array = input_file.readlines()

    for line in file_lines_array:
        print(line)
with open("data.txt") as input_file:
    for line in input_file:
        print(line)

The splitlines() example removes the \n newline character from the line whereas the other two do not.

Report a Glow concern
Cookie policy  Privacy policy