Read a File Line by Line in Python

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.

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:

  1. Display string without new lines. In this situation just change print(line) to print(line.strip()).
  2. 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].

Another way is even simpler because you don’t have to create the list of strings, but only a string variable.

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.

output

Sunday