How to Read Lines From a File in Python

Reading files is a necessary task in any programming linguistic communication. Whether it's a database file,  prototype, or chat log, having the ability to read and write files greatly enhances what we tin can with Python.

Before nosotros can create an automatic audiobook reader or website, we'll need to master the nuts. Later all, no i ever ran before they crawled.

To complicate matters, Python offers several solutions for reading files. We're going to cover the near common procedures for reading files line past line in Python. Once you lot've tackled the basics of reading files in Python, yous'll be better prepared for the challenges that prevarication ahead.

Yous'll exist happy to learn that Python provides several functions for reading, writing, and creating files. These functions simplify file direction by treatment some of the work for united states, backside the scenes.

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

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

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

This method also returns a list of all the lines in the file. We can use readlines() to chop-chop read an entire file.

For example, let's say we have a file containing basic information near employees at our company. Nosotros need to read this file and do something with the information.

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

Name: Emerge Rain
age: 31
Occupation: Senior Developer

Example 1: Using readlines() to read a file

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

Output

            ['Proper name: Marcus Gaye\n', 'Age: 25\northward', 'Occupation: Web Programmer\due north', '\northward', 'Proper name: Sally Rain\n', 'historic period: 31\n', 'Occupation: Senior Programmer\northward']          

readline() vs readlines()

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

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

Consider the following text file:

wise_owl.txt
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 tin can't we all exist like that wise one-time bird?

Nosotros can apply readline() to get the first line of the text document. Dissimilar readlines(), only a unmarried line will exist printed when we use the readline() method to read the file.

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

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

Output

            A wise sometime owl lived in an oak.                      

The readline() method only retrieves a single line of text. Use readline() if yous need to read all the lines at once.

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

Output

['A wise old owl lived in an oak.\north', 'The more than he saw the less he spoke.\n', 'The less he spoke the more than he heard.\due north', "Why can't we all exist like that wise old 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 tin 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:         intermission;     print(next_line.strip())  file.close()                      

Output

A wise old 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 one-time bird?

Beware of infinite loops

A word of alert when working with while loops is in order. Exist conscientious to add a termination case for the loop, otherwise yous'll finish up looping forever. Consider the post-obit instance:

            while True:     print("Groundhog Mean solar day!")                      

Executing this lawmaking will cause Python to fall into an infinite loop, printing "Groundhog Day" until the end of time. When writing code like this, always provide a fashion to go out the loop.

If you find that you've accidentally executed an infinite loop, you tin can escape information technology in the terminal past tapping Command+C on your keyboard.

Reading a file object in Python

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

Here's the listing 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 Brownish
66 Ashley Ave.
Chaska, MN 55318

Whenever nosotros open a file object, we can utilise 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 customer. It's very of import that the information is in the form of a Python list. We'll need to suspension the file into separate addresses and store them in a list before we can go on.

Example five: 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 3 lines     if i > 2:         i = 0         address_list.append(current_address)         current_address = ""     else:         # add the line to the current address         current_address += line         i += 1  # utilise a for-in loop to impress the list of addresses for address in address_list:     print(accost)  file.close()                      

Reading a file with the Context Manager

File management is a delicate process in any programming language. Files must be handled with care to forbid their abuse. When a file is opened, intendance must be taken to ensure the resource is afterward closed.

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

Introducing the with block

Whenever we open a file in Python, it'southward important that we remember to close information technology. A method like readlines() will work okay for pocket-sized files, but what if we have a more complex document? Using Python with statements will 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 block.
  • One time the cake executes, Python automatically closes the file resource.
  • The context has the same scope as the with statement.

Permit's practice using the with argument past reading an email we have saved every bit a text file.

e-mail.txt
Dear Valued Customer,
Give thanks you for reaching out to united states of america most the issue with the product that you purchased. Nosotros are eager to address any concerns you may have about our products.

We want to brand sure that you lot are completely satisfied with your purchase. To that terminate, nosotros offer a thirty-day, money-back guarantee on our unabridged inventory. But render the product and we'll happily refund the price of your purchase.

Thank you,
The ABC Company

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

This fourth dimension a for loop is used to read the lines of the file. When we're using the Context Director, the file is automatically airtight when it's handler goes out of scope. When the role 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. Nosotros've learned in that location is a big difference between the readline() and readlines() methods, and that nosotros can use a for loop to read the contents of a file object.

Nosotros also learned how to utilize the with statement to open up and read files. We saw how the context manager was created to make treatment files safer and easier in Python.

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

If you'd like to acquire well-nigh programming with Python, follow the links below to view more cracking lessons from Python for Beginners.

Related Posts

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

Recommended Python Training

Form: Python 3 For Beginners

Over 15 hours of video content with guided educational activity for beginners. Learn how to create real world applications and principal the basics.

brownhiguess.blogspot.com

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

0 Response to "How to Read Lines From a File in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel