Skip to content Skip to sidebar Skip to footer

Read Line by Line From File Python

Reading files is a necessary job in whatsoever programming language. Whether information technology's a database file,  prototype, or chat log, having the power to read and write files profoundly enhances what nosotros tin with Python.

Before we can create an automatic audiobook reader or website, we'll need to master the basics. After all, no one ever ran before they crawled.

To complicate matters, Python offers several solutions for reading files. We're going to cover the most common procedures for reading files line by line in Python. Once you've tackled the nuts of reading files in Python, you'll be better prepared for the challenges that lie 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 usa, behind the scenes.

We can use many of these Python functions to read a file line past line.

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

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

This method too returns a list of all the lines in the file. Nosotros can utilise readlines() to speedily read an entire file.

For case, permit's say we have a file containing basic data about employees at our company. We demand to read this file and do something with the data.

employees.txt
Name: Marcus Gaye
Age: 25
Occupation: Web Developer

Name: Sally Rain
age: 31
Occupation: Senior Programmer

Case one: Using readlines() to read a file

            # open the data file file = open("employees.txt") # read the file every bit a listing information = file.readlines() # shut the file file.shut()  impress(information)                      

Output

            ['Name: Marcus Gaye\north', 'Historic period: 25\n', 'Occupation: Spider web Programmer\n', '\due north', 'Name: Emerge Rain\n', 'age: 31\northward', 'Occupation: Senior Developer\n']          

readline() vs readlines()

Different its counterpart, the readline() method only returns a single line from a file. The realine() method will likewise add a trailing newline character to the end of the string.

With the readline() method, nosotros also have the option of specifying a length for the returned line. If a size is non provided, the entire 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 similar that wise old bird?

We can utilize readline() to become the first line of the text document. Unlike readlines(), but a single line will be printed when we utilise the readline() method to read the file.

Example two: Read a unmarried line with the readline() method

            file = open up("wise_owl.txt") # get the outset line of the file line1 = file.readline() impress(line1) file.shut()          

Output

            A wise former owl lived in an oak.                      

The readline() method simply retrieves a single line of text. Use readline() if y'all demand to read all the lines at once.

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

Output

['A wise old owl lived in an oak.\n', 'The more he saw the less he spoke.\n', 'The less he spoke the more he heard.\n', "Why tin't we all be like that wise old bird?\n"]

Using a While Loop to Read a File

It'south possible to read a file using loops also. Using the aforementioned 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 True:     next_line = file.readline()      if not next_line:         pause;     print(next_line.strip())  file.close()                      

Output

A wise old 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 infinite loops

A word of warning when working with while loops is in gild. Be careful to add a termination case for the loop, otherwise y'all'll end upward looping forever. Consider the following case:

            while True:     print("Groundhog Day!")                      

Executing this lawmaking volition crusade Python to fall into an infinite loop, printing "Groundhog Solar day" until the end of time. When writing code similar this, always provide a mode to leave the loop.

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

Reading a file object in Python

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

Here's 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 Farm St.
Rockledge, FL 32955

Prudence Dark-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.

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

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

Unfortunately, this solution will non work for our client. It's very important that the data is in the form of a Python listing. We'll need to suspension the file into carve up addresses and store them in a list before nosotros tin go along.

Example 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 a new address every three lines     if i > 2:         i = 0         address_list.suspend(current_address)         current_address = ""     else:         # add the line to the current accost         current_address += line         i += i  # use a for-in loop to print the list of addresses for address in address_list:     print(address)  file.shut()                      

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 corruption. When a file is opened, care must be taken to ensure the resource is later closed.

And there is a limit to how many files can be opened at once in Python. In order to avert these problems, Python provides us with the Context Manager.

Introducing the with block

Whenever we open up a file in Python, information technology's important that we remember to close it. A method like readlines() volition work okay for minor files, but what if we accept a more complex document? 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.
  • One time the block executes, Python automatically closes the file resource.
  • The context has the same scope as the with argument.

Let's practice using the with statement by reading an e-mail we have saved as a text file.

email.txt
Dear Valued Customer,
Thanks for reaching out to us about the upshot with the product that you purchased. We are eager to accost any concerns you may have about our products.

We desire to make sure that you are completely satisfied with your purchase. To that end, we offer a 30-twenty-four hour period, money-back guarantee on our entire inventory. Only return the product and nosotros'll happily refund the cost of your purchase.

Give thanks you,
The ABC Company

            code example # open up file with open("e-mail.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 Managing director, the file is automatically closed when it's handler goes out of scope. When the function is finished with the file, with argument ensures the resources 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 large departure between the readline() and readlines() methods, and that nosotros can use a for loop to read the contents of a file object.

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

Several examples were provided to illustrated the various forms of file treatment bachelor in Python. Accept time to explore the examples and don't exist afraid to experiment with the code if you lot don't understand something.

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

Related Posts

  • Using Python try except to handle errors
  • How to use Python split up string to improve your coding skills
  • Using Python string chain for meliorate readability

Recommended Python Training

Course: Python three For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real globe applications and master the basics.

hillardmoread.blogspot.com

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

Post a Comment for "Read Line by Line From File Python"