You can open a file and read it line by line very easily with a few lines of code thanks to the read and readlines functions.
Read text file line by line, add to a list, and display values
First, create a text file called days.txt with the days of the week.
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Now, execute the following code.
1 2 3 4 5 6 7 |
f = open('days.txt', 'r') list_of_lines = f.readlines() for line in list_of_lines: print(line) f.close() |
The open() function opens the file to read-only (r).
All the lines in a file are saved in the list called list_of_lines, which consists of the following strings.
After you execute the code, you will notice that in the console there are two new lines between each string. This happens because each value in the file is written in a new line and the print() function adds another one.
After all, operations are made, the file is closed.
output Monday Tuesday Wednesday Thursday Friday Saturday Sunday
You have two ways you can deal with this problem:
- Display string without new lines. In this situation just change print(line) to print(line.strip()).
- The second way is to write values to a list without newline characters. To do it, change readlines() to f.read().splitlines().
Each method gives the following output:
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Read only the first line
To display only the first line of a file, you need to access the first element of the list. Indexing in Python begins from 0, so the first element will be list_of_lines[0].
1 2 3 4 5 6 |
f = open('days.txt', 'r') list_of_lines = f.read().splitlines() print(list_of_lines[0]) f.close() |
Another way is even simpler because you don’t have to create the list of strings, but only a string variable.
1 2 3 4 5 6 |
f = open('days.txt', 'r') first_line = f.readline().strip() print(first_line) f.close() |
Both scripts will return the following code.
Monday
Read only the last line
To get the last element from a file, you can get the last element from the list.
1 2 3 4 5 6 |
f = open('days.txt', 'r') list_of_lines = f.read().splitlines() print(list_of_lines[-1]) f.close() |
output
Sunday