Read a file in Python

With a few lines of code, you can read a file in Python.

You have to specify an absolute path to the file you want to read, or you can specify the current working directory.

Read file using an absolute path

Create a text file you want to read from. I created a simple three-line text inside my_file.txt in D:\temp. The absolute path to the file is D:\temp\my_file.txt.

Let’s read and display all lines inside a file:

full_path = 'd:\\temp\\my_file.txt'

with open(full_path) as file:
    lines_of_text = file.readlines()

print(lines_of_text)

The result of this code:

['This is just a simple text.\n', 'This is the second line.\n', 'And this is the third one.']

lines_of_text is a list of strings. At the end of each element, but the last, there is a new line character ‘\n’. It means that the cursor moves to the next line after writing or displaying the string.

for line in lines_of_text:
    print(line)

This is how it looks like if you print each line from the list:

This is just a simple text.

This is the second line.

And this is the third one.

There is an additional newline character between lines because the print function adds it automatically.

There are at least two ways you can do it.

Remove the newline character inside print

If you want to keep newline characters, but only remove them while displaying the result, you can use this code:

for line in lines_of_text:
    print(line.strip())

It will remove newline characters and redundant spaces from the string.

This is just a simple text.
This is the second line.
And this is the third one.

Remove the newline character inside print

If you want to create a list with lines of text from the file, but without the new line characters, you have to change the readlines function.

full_path = 'd:\\temp\\my_file.txt'

with open(full_path) as file:
    lines_of_text = file.read().splitlines()

for line in lines_of_text:
    print(line)

The result is the same as before:

This is just a simple text.
This is the second line.
And this is the third one.

Using relative path

If you want to use relative paths, you have to make sure that the file is inside the current working directory.

To set the directory, you have to import the os module and assign a new path.

import os
os.chdir('d:\\temp\\')

The new code is going to look like this:

import os
os.chdir('d:\\temp\\')

file_name = 'my_file.txt'

with open(file_name) as file:
    lines_of_text = file.read().splitlines()

for line in lines_of_text:
    print(line)

You can change double backslashes to single forward slashes inside paths:

full_path = 'd:/temp/my_file.txt'