Python Read Text File Line by Line Count
Tabular array of Contents Hide
- Steps to Read Text File in Python
- Python open() office
- Methods for Reading file contents
- Python close() role
- 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
- Instance 3 – Read a single line in a file using the readline() part
- Example 4- Read text file line by line using the readline() part
- Example five – Read all the lines as a list in a file using the readlines() function
Python provides built-in functions to perform file operations, such equally creating, reading, and writing files. At that place are mainly two types of files that Python 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 demand to follow the below steps.
Step i: The file needs to be opened for reading using the open()
method and pass a file path to the function.
Step 2: The next step is to read the file, and this can exist achieved using several congenital-in methods such as read()
, readline()
, readlines()
.
Step iii: Once the read operation is performed, the text file must be airtight using the close()
role.
At present that nosotros have seen the steps to read the file content let'southward sympathise each of these methods before getting into examples.
Python open()
function
The open up()
part opens the file if possible and returns the corresponding file object.
Syntax – open(file, style='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The open up()
function has a lot of parameters. Let's accept a look at the necessary params for reading the text file. It opens the file in a specified mode and returns a file object.
Parameters
- file – path like object which represents the file path
- fashion (Optional) – The
way
is an optional parameter. Information technology'due south a string that specifies the mode in which you want to open the file.
Mode | Description |
---|---|
'r' | Open up a file for read mode (default if mode is not specified) |
'w' | Open a file for writing. Python volition create a new file if does not exist or truncates a file content if file exists |
'x' | Open a file for exclusive creation. |
'a' | Open up a file for appending the text. Creates a new file if file does not exist. |
't' | Open a file in text style. (default) |
'b' | Open a file in binary manner. |
'+' | Open a file for updating (reading and writing) |
Example
file = open('C:\hello.txt','r')
Methods for Reading file contents
There are three ways to read data from a text file.
-
read()
: Theread()
role returns the read bytes in the course of string. This method is useful when you accept a pocket-size file, and you want to read the specified bytes or entire file and store information technology into a string variable. -
readline()
: Thereadline()
role returns one line from a text file and retuns in the course of string. -
readlines()
: Thereadlines()
function reads all the lines from the text file and returns each line as a string element in a list.
Python close()
function
The file will remain open up until you close the file using the close()
function. It is a must and all-time exercise to perform this operation after reading the information from the file as it frees up the retentiveness space acquired by that file. Otherwise, it may cause an unhandled exception.
Examples for Reading a Text file in Python
Case 1 – Read the unabridged text file using the read()
function
In the below example, nosotros are reading the entire text file using the read()
method. The file tin can be opened in the read mode or in a text mode to read the data, and it can be stored in the cord variable.
# Program to read the entire file using read() part file = open("python.txt", "r") content = file.read() print(content) file.close() # Program to read the entire file (accented path) using read() part file = open("C:/Projects/Tryouts/python.txt", "r") content = file.read() print(content) file.close()
Output
Dear User, Welcome to Python Tutorial Have a great learning !!! Cheers
Instance 2 – Read the specific length of characters in a text file using the read()
role
There are times where you need to read the specific bytes in a file. In that instance, yous tin can utilise the read()
function 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
Dear User, Welcome
Example 3 – Read a unmarried line in a file using the readline()
function
If you want to read a single line in a file, and then you could accomplish this using readline()
function. You also apply this method to recollect specific bytes of characters in a line, like to the read()
method.
# Program to read unmarried line in a file using readline() function file = open("python.txt", "r") content = file.readline() print(content) file.close()
Output
Dearest User,
Example iv- Read text file line by line using the readline()
function
If you want to traverse the file line by line and output in any format, then you could utilize the while loop with the readline()
method as shown below. This is the most effective style to read the text file line past line in Python.
# Program to read all the lines in a file using readline() function file = open("python.txt", "r") while Truthful: content=file.readline() if not content: break print(content) file.shut()
Output
Dear User, Welcome to Python Tutorial Take a nifty learning !!! Thanks
Example 5 – Read all the lines equally a listing 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 tin use the list to traverse and excerpt the specified content from the listing.
# Programme 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.close()
Output
['Love User,\northward', 'Welcome to Python Tutorial\n', 'Have a great learning !!!\northward', 'Cheers']
Sign Upwardly for Our Newsletters
Source: https://itsmycode.com/python-read-text-file/
0 Response to "Python Read Text File Line by Line Count"
Post a Comment