Read Txt File Line by Line in Python

Reading files is a necessary task in whatsoever programming linguistic communication. Whether it's a database file,  image, or chat log, having the power to read and write files profoundly enhances what we tin with Python.

Earlier we can create an automated audiobook reader or website, we'll demand to master the nuts. Subsequently all, no one ever ran earlier they crawled.

To complicate matters, Python offers several solutions for reading files. We're going to comprehend the most mutual procedures for reading files line by line in Python. One time you've tackled the nuts of reading files in Python, y'all'll be amend prepared for the challenges that prevarication ahead.

You'll be happy to learn that Python provides several functions for reading, writing, and creating files. These functions simplify file management past handling some of the work for the states, behind the scenes.

Nosotros can utilize many of these Python functions to read a file line by line.

Read a File Line past Line with the readlines() Method

Our first arroyo to reading a file in Python will be the path of least resistance: the readlines() method. This method will open a file and divide its contents into separate lines.

This method also returns a list of all the lines in the file. Nosotros can employ readlines() to quickly read an unabridged file.

For example, let'southward say we accept a file containing basic information about employees at our company. We need to read this file and do something with the data.

employees.txt
Proper name: Marcus Gaye
Age: 25
Occupation: Web Developer

Proper name: Sally Rain
historic period: 31
Occupation: Senior Developer

Example ane: Using readlines() to read a file

            # open the data file file = open up("employees.txt") # read the file as a list information = file.readlines() # close the file file.close()  print(data)                      

Output

            ['Name: Marcus Gaye\n', 'Age: 25\n', 'Occupation: Web Developer\due north', '\n', 'Proper noun: Sally Rain\n', 'age: 31\n', 'Occupation: Senior Programmer\northward']          

readline() vs readlines()

Unlike its counterpart, the readline() method only returns a single line from a file. The realine() method will also add a trailing newline graphic symbol to the stop of the string.

With the readline() method, we also have the selection of specifying a length for the returned line. If a size is not provided, the unabridged line will be read.

Consider the following text file:

wise_owl.txt
A wise one-time owl lived in an oak.
The more than he saw the less he spoke.
The less he spoke the more he heard.
Why can't we all be like that wise old bird?

We can apply readline() to become the first line of the text certificate. Unlike readlines(), only a unmarried line will be printed when we use the readline() method to read the file.

Case two: Read a single line with the readline() method

            file = open("wise_owl.txt") # get the first line of the file line1 = file.readline() print(line1) file.close()          

Output

            A wise former owl lived in an oak.                      

The readline() method but retrieves a single line of text. Utilize readline() if y'all need to read all the lines at once.

            file = open("wise_owl.txt") # store all the lines in the file every bit a list lines = file.readlines() print(lines) file.close()                      

Output

['A wise former owl lived in an oak.\n', 'The more he saw the less he spoke.\due north', 'The less he spoke the more than he heard.\n', "Why can't we all exist like that wise former bird?\n"]

Using a While Loop to Read a File

It's possible to read a file using loops as well. Using the same wise_owl.txt file that we made in the previous section, we can read every line in the file using a while loop.

Example 3: Reading files with a while loop and readline()

            file = open("wise_owl.txt",'r') while Truthful:     next_line = file.readline()      if not next_line:         break;     print(next_line.strip())  file.shut()                      

Output

A wise erstwhile owl lived in an oak.
The more he saw the less he spoke.
The less he spoke the more he heard.
Why can't we all be like that wise sometime bird?

Beware of space loops

A word of warning when working with while loops is in society. Be careful to add a termination instance for the loop, otherwise you lot'll finish up looping forever. Consider the post-obit case:

            while Truthful:     print("Groundhog Day!")                      

Executing this code volition cause Python to fall into an space loop, printing "Groundhog Twenty-four hour period" until the terminate of time. When writing code similar this, always provide a manner to exit the loop.

If y'all find that yous've accidentally executed an space loop, you can escape it in the terminal by tapping Control+C on your keyboard.

Reading a file object in Python

It's too possible to read a file in Python using a for loop. For example, our client has given us a list of addresses of previous customers. We need to read the data using Python.

Here'southward the list of clients:

address_list.txt
Bobby Dylan
111 Longbranch Ave.
Houston, TX 77016

Sam Garfield
9805 Border Rd.
New Brunswick, NJ 08901

Penny Lane
408 2nd Lane
Lindenhurst, NY 11757

Marcus Gaye
622 Shub Subcontract St.
Rockledge, FL 32955

Prudence Brown
66 Ashley Ave.
Chaska, MN 55318

Whenever we open a file object, we can use a for loop to read its contents using the in keyword. With the in keyword, we can loop through the lines of the file.

Instance 4: Using a for loop to read the lines in a file

            # open the file  address_list = open("address_list.txt",'r')  for line in address_list:     print(line.strip())  address_list.close()                      

Unfortunately, this solution volition not work for our client. It's very of import that the data is in the form of a Python listing. Nosotros'll need to break the file into separate addresses and shop them in a list before we tin continue.

Instance 5: Reading a file and splitting the content into a list

            file = open("address_list.txt",'r') address_list = [] i = 0 current_address = "" for line in file:     # add together a new address every 3 lines     if i > 2:         i = 0         address_list.append(current_address)         current_address = ""     else:         # add the line to the current accost         current_address += line         i += 1  # employ a for-in loop to print the listing of addresses for address in address_list:     print(address)  file.close()                      

Reading a file with the Context Manager

File management is a delicate procedure in any programming language. Files must be handled with care to forestall their abuse. When a file is opened, intendance must exist taken to ensure the resources is later closed.

And at that place is a limit to how many files can be opened at once in Python. In order to avoid these problems, Python provides united states with the Context Manager.

Introducing the with cake

Whenever we open a file in Python, it'due south important that we remember to close it. A method similar readlines() will piece of work okay for small files, but what if we have a more complex certificate? Using Python with statements volition ensure that files are handled safely.

  • The with statement is used for safely accessing resource files.
  • Python creates a new context when it encounters the with cake.
  • In one case the cake executes, Python automatically closes the file resources.
  • The context has the same scope as the with statement.

Let's practise using the with statement by reading an email we have saved as a text file.

email.txt
Dear Valued Client,
Thanks for reaching out to us nearly the issue with the product that you lot purchased. We are eager to address any concerns you may have nigh our products.

Nosotros want to make certain that you are completely satisfied with your purchase. To that end, we offer a 30-day, money-back guarantee on our entire inventory. Simply render the production and we'll happily refund the price of your purchase.

Thank you,
The ABC Company

            code example # open file with open("email.txt",'r') as email:     # read the file with a for loop     for line in email:         # strip the newline character from the line         print(line.strip())                      

This time a for loop is used to read the lines of the file. When we're using the Context Director, the file is automatically closed when it's handler goes out of telescopic. When the function is finished with the file, with statement ensures the resource is handled responsibly.

Summary

We've covered several ways of reading files line by line in Python. We've learned at that place is a big departure between the readline() and readlines() methods, and that we tin can use a for loop to read the contents of a file object.

Nosotros also learned how to use the with argument to open and read files. We saw how the context manager was created to make handling files safer and easier in Python.

Several examples were provided to illustrated the various forms of file handling available in Python. Take fourth dimension to explore the examples and don't be afraid to experiment with the code if yous don't understand something.

If you'd like to learn about programming with Python, follow the links beneath to view more great lessons from Python for Beginners.

Related Posts

  • Using Python try except to handle errors
  • How to use Python dissever cord to amend your coding skills
  • Using Python string concatenation for meliorate readability

Recommended Python Training

Course: Python three For Beginners

Over 15 hours of video content with guided instruction for beginners. Acquire how to create real world applications and master the nuts.

alaimothessaft.blogspot.com

Source: https://www.pythonforbeginners.com/files/4-ways-to-read-a-text-file-line-by-line-in-python

0 Response to "Read Txt File Line by Line in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel