How to Read Data From a Text File in Python
Table of Contents Hide
- Steps to Read Text File in Python
- Python open up() function
- Methods for Reading file contents
- Python close() function
- Examples for Reading a Text file in Python
- Example 1 – Read the entire text file using the read() function
- Example 2 – Read the specific length of characters in a text file using the read() function
- Example 3 – Read a unmarried line in a file using the readline() function
- Example four- Read text file line by line using the readline() function
- Example five – Read all the lines as a list in a file using the readlines() role
Python provides built-in functions to perform file operations, such every bit creating, reading, and writing files. In that location are mainly two types of files that Python tin can handle, normal text files and binary files. In this tutorial, we will take a look at how to read text files in Python.
Steps to Read Text File in Python
In Python, to read a text file, yous need to follow the below steps.
Step ane: The file needs to be opened for reading using the open up()
method and laissez passer a file path to the role.
Footstep 2: The next pace is to read the file, and this can be accomplished using several built-in methods such as read()
, readline()
, readlines()
.
Step 3: Once the read operation is performed, the text file must be closed using the close()
function.
Now that we accept seen the steps to read the file content let's understand each of these methods earlier getting into examples.
Python open up()
function
The open()
function opens the file if possible and returns the corresponding file object.
Syntax – open(file, fashion='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The open()
function has a lot of parameters. Let'southward take a look at the necessary params for reading the text file. Information technology opens the file in a specified manner and returns a file object.
Parameters
- file – path similar object which represents the file path
- manner (Optional) – The
style
is an optional parameter. It's a cord that specifies the style in which you lot want to open the file.
Mode | Description |
---|---|
'r' | Open up a file for read manner (default if manner is not specified) |
'w' | Open a file for writing. Python will create a new file if does not exist or truncates a file content if file exists |
'x' | Open up a file for exclusive creation. |
'a' | Open a file for appending the text. Creates a new file if file does not be. |
't' | Open a file in text fashion. (default) |
'b' | Open a file in binary style. |
'+' | Open a file for updating (reading and writing) |
Example
file = open up('C:\how-do-you-do.txt','r')
Methods for Reading file contents
There are three ways to read data from a text file.
-
read()
: Theread()
function returns the read bytes in the grade of cord. This method is useful when y'all have a small file, and you desire to read the specified bytes or unabridged file and store it into a cord variable. -
readline()
: Thereadline()
office returns one line from a text file and retuns in the class of string. -
readlines()
: Thereadlines()
function reads all the lines from the text file and returns each line as a string chemical element in a listing.
Python close()
office
The file will remain open up until you close the file using the close()
function. It is a must and best practise to perform this operation after reading the information from the file as information technology frees up the memory space acquired by that file. Otherwise, it may cause an unhandled exception.
Examples for Reading a Text file in Python
Case ane – Read the unabridged text file using the read()
office
In the below example, we are reading the unabridged text file using the read()
method. The file can be opened in the read style or in a text manner to read the data, and it can exist stored in the string variable.
# Program to read the entire file using read() function file = open up("python.txt", "r") content = file.read() print(content) file.close() # Program to read the entire file (absolute path) using read() function file = open("C:/Projects/Tryouts/python.txt", "r") content = file.read() print(content) file.close()
Output
Love User, Welcome to Python Tutorial Take a great learning !!! Cheers
Example 2 – Read the specific length of characters in a text file using the read()
function
At that place are times where you lot need to read the specific bytes in a file. In that case, you can utilize the read()
part by specifying the bytes. The method will output only the specified bytes of characters in a file, as shown below.
# Program to read the specific length # of characters in a file using read() office file = open("python.txt", "r") content = file.read(xx) print(content) file.close()
Output
Beloved User, Welcome
Case 3 – Read a single line in a file using the readline()
function
If yous want to read a unmarried line in a file, then y'all could achieve this using readline()
function. You as well use this method to retrieve specific bytes of characters in a line, similar to the read()
method.
# Program to read single line in a file using readline() function file = open("python.txt", "r") content = file.readline() impress(content) file.shut()
Output
Dear User,
Instance 4- Read text file line by line using the readline()
function
If you desire to traverse the file line by line and output in any format, so you could apply the while loop with the readline()
method as shown below. This is the most effective way to read the text file line by line in Python.
# Plan to read all the lines in a file using readline() office file = open("python.txt", "r") while True: content=file.readline() if not content: suspension print(content) file.close()
Output
Dear User, Welcome to Python Tutorial Accept a great learning !!! Cheers
Example 5 – Read all the lines as a list in a file using the readlines()
function
The readlines()
method volition read all the lines in the file and outputs in a list of strings, as shown below. Later you can use the list to traverse and extract the specified content from the list.
# Program to read all the lines as a list in a file # using readlines() role file = open up("python.txt", "r") content=file.readlines() print(content) file.shut()
Output
['Love User,\n', 'Welcome to Python Tutorial\n', 'Accept a great learning !!!\north', 'Cheers']
Sign Up for Our Newsletters
How to Read Data From a Text File in Python
Source: https://itsmycode.com/python-read-text-file/