Reading from a file

Published

2023-07-31

Reading from a file

Let’s say we have a .txt file called hello.txt in the same directory as a Python file we just created. We wish to open the file, read its content and assign it to a variable, and print that variable to the console. This is how we would do this:

>>> with open('hello.txt') as f:
...     s = f.read()
...
>>> print(s)
Hello World!

It’s often useful to read one line at a time into a list.

>>> lines = []
>>> with open('poem.txt') as f:
...    for line in f:
...        lines.append(line)
...
>>> print(lines)
["Flood-tide below me!\n", "I see you face to face\n",
"Clouds of the west--\n", "Sun there half an hour high--\n",
"I see you also face to face.\n"]

Now, when we look at the data this way, we see clearly that newline characters are included at the end of each line. Sometimes we wish to remove this. For this we use the string method .strip().

>>> lines = []
>>> with open('poem.txt') as f:
...    for line in f:
...        lines.append(line.strip())
...
>>> print(lines)
["Flood-tide below me!", "I see you face to face",
"Clouds of the west--", "Sun there half an hour high--",
"I see you also face to face."]
>>>

The string method .strip() without any argument removes any leading or trailing whitespace, newlines, or return characters from a string.

If you only wish to remove newlines ('\n'), just use s.strip('\n') where s is some string.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).