Read a file in Python
This post will discuss how to read a text file in Python.
1. Using open() function
A simple solution is to open the file in reading mode 'r' using the built-in open() function. Since the mode in which the file is opened defaults to 'r', you can skip it.
|
1 2 3 4 5 |
f = open('file.txt') text = f.read() print(text) f.close() |
The above syntax requires you to explicitly close the file using the close() function. This is not considered Pythonic, and you should use the with keyword, which automatically closes the file once it is done with, even when an exception is raised. Here’s an equivalent code using the with statement:
|
1 2 3 4 |
with open('file.txt') as f: text = f.read() print(text) |
2. Using pathlib module
You can also use the pathlib module with Python 3.4. The Path.read_text() function opens the file in text mode, reads it, and close the file.
|
1 2 3 4 |
import pathlib text = pathlib.Path('file.txt').read_text() print(text) |
3. Using io module
Finally, you can call the io.open() function, which is an alias for the built-in open() function.
|
1 2 3 4 5 6 |
import io with io.open("file.txt", mode='r', encoding='utf-8') as f: text = f.read() print(text) |
That’s all about reading a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)