Reading Files

After you have opened a file you can read from it with the read() method.

i[akraker@localhost:~]$ echo 'Hello, world!' > hello.txt
i[akraker@localhost:~]$ cat hello.txt
Hello, world!
i[akraker@localhost:~]$ python
Python 3.9.7 (default, Aug 30 2021, 00:00:00)
[GCC 11.2.1 20210728 (Red Hat 11.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
i>>> helloFile = open('/home/akraker/hello.txt')
i>>> helloContent = helloFile.read()
i>>> helloContent
'Hello, world!\n'

The read() method just get’s one long string from the file.

To get a list of lines from the file use readlines().

i>>> from pathlib import Path
i>>> sonnetFile = open(Path.cwd() / 'sonnet29.txt')
i>>> sonnetFile.readlines()
["When, in disgrace with fortune and men's eyes,\n", 'I all alone beweep my outcast state,\n', 'A
nd trouble deaf heaven with my bootless cries,\n', 'And look upon myself and curse my fate,\n']

Using the with statement to read files #

You can use the with statement to read and print files.

pi_digits.txt

3.1415926535
8979323846
2643383279
i>>> with open('pi_digits.txt') as file_object:
i...    contents = file_object.read()
i...
i>>> print(contents)
3.1415926535
8979323846
2643383279

Reading line by line #

It’s common to want to examine each line individually and do something to that line, for loops come in handy for this:

filename = 'pi_digits.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line)

Note, assigning a variable to the file-path is a common convention.

i>>> with open('pi_digits.txt') as file_object:
i...    contents = file_object.read()
i...
i>>> print(contents)
3.1415926535
8979323846
2643383279

Making a list of lines from a file #

filename = 'pi_digits.txt'
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())