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:

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:

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.

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:

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: