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:

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.

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:

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.

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.

The new code is going to look like this:

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