Python Tutorials · File Handling

Python Read Files

Learn all about Python Read Files in this comprehensive tutorial.

5 min read intermediate
  • Assume we have the following file, located in the same folder as Python:
  • You can also use the with statement when opening a file:
  • It is a good practice to always close the file when you are done with it.
  • By default the read() method returns the whole text, but you can also specify how many characters you want to return:
  • You can return one line by using the readline() method:

Open a File on the Server

Assume we have the following file, located in the same folder as Python:

python

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

python

If the file is located in a different location, you will have to specify the file path, like this:

python

Using the with statement

You can also use the with statement when opening a file:

python

Then you do not have to worry about closing your files, the with statement takes care of that.

Close Files

It is a good practice to always close the file when you are done with it.

If you are not using the with statement, you must write a close statement in order to close the file:

python
Note: Note: You should always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

python

Read Lines

You can return one line by using the readline() method:

python

By calling readline() two times, you can read the two first lines:

python

By looping through the lines of the file, you can read the whole file, line by line:

python

Module quiz

2 questions
1

Which of the following is true about Python Read Files?

2

What is the most common pitfall when working with Python Read Files?

Answer all questions to submit.