How to Read Text File Python as Lines
Reading files is a necessary task in any programming language. Whether it'due south a database file, paradigm, or chat log, having the ability to read and write files greatly enhances what nosotros can with Python.
Before we can create an automated audiobook reader or website, we'll need to master the basics. After all, no ane always ran before they crawled.
To complicate matters, Python offers several solutions for reading files. We're going to cover the virtually mutual procedures for reading files line by line in Python. Once you've tackled the basics of reading files in Python, you'll be better prepared for the challenges that lie ahead.
You lot'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 u.s., behind the scenes.
Nosotros can utilize many of these Python functions to read a file line past line.
Read a File Line by Line with the readlines() Method
Our get-go approach to reading a file in Python volition be the path of least resistance: the readlines() method. This method volition open a file and dissever its contents into split up lines.
This method also returns a list of all the lines in the file. Nosotros can use readlines() to apace read an unabridged file.
For example, permit'south say we accept a file containing bones information about employees at our company. We need 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
Example 1: Using readlines() to read a file
# open the information file file = open up("employees.txt") # read the file equally a list data = file.readlines() # shut the file file.shut() print(data)
Output
['Name: Marcus Gaye\due north', 'Age: 25\n', 'Occupation: Web Programmer\n', '\n', 'Proper name: Sally Rain\n', 'historic period: 31\due north', 'Occupation: Senior Developer\n']
readline() vs readlines()
Unlike its analogue, the readline() method only returns a single line from a file. The realine() method volition also add a trailing newline graphic symbol to the end of the cord.
With the readline() method, nosotros also have the choice of specifying a length for the returned line. If a size is not provided, the entire line volition exist 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 can't we all be like that wise onetime bird?
We can employ readline() to get the showtime line of the text document. Different readlines(), just a unmarried line will be printed when we use the readline() method to read the file.
Instance two: Read a single line with the readline() method
file = open("wise_owl.txt") # get the showtime line of the file line1 = file.readline() impress(line1) file.close()
Output
A wise old owl lived in an oak.
The readline() method but retrieves a single line of text. Use readline() if you need 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() impress(lines) file.close()
Output
['A wise sometime 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 can'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 likewise. 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 iii: Reading files with a while loop and readline()
file = open("wise_owl.txt",'r') while Truthful: next_line = file.readline() if non next_line: break; impress(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 tin't we all exist like that wise old bird?
Beware of infinite loops
A word of alarm when working with while loops is in order. Exist careful to add a termination case for the loop, otherwise y'all'll end up looping forever. Consider the following example:
while True: print("Groundhog Day!")
Executing this code will cause Python to fall into an infinite loop, printing "Groundhog Twenty-four hour period" until the end of time. When writing lawmaking like this, always provide a way to exit the loop.
If you find that you've accidentally executed an infinite loop, yous can escape it in the concluding by tapping Control+C on your keyboard.
Reading a file object in Python
Information technology's also possible to read a file in Python using a for loop. For case, our client has given the states a list of addresses of previous customers. Nosotros demand to read the data 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 Brownish
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, nosotros can loop through the lines of the file.
Case 4: Using a for loop to read the lines in a file
# open up the file address_list = open("address_list.txt",'r') for line in address_list: print(line.strip()) address_list.close()
Unfortunately, this solution will not piece of work for our client. It's very important that the data is in the form of a Python list. We'll need to suspension the file into separate addresses and store them in a listing before nosotros can keep.
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.append(current_address) current_address = "" else: # add together the line to the current accost current_address += line i += 1 # use a for-in loop to print the list of addresses for address in address_list: print(accost) file.shut()
Reading a file with the Context Manager
File management is a frail process in any programming language. Files must exist handled with care to prevent their corruption. When a file is opened, care must be taken to ensure the resources is later closed.
And there is a limit to how many files can be opened at in one case in Python. In society to avoid these problems, Python provides united states of america with the Context Manager.
Introducing the with cake
Whenever we open up a file in Python, it's important that nosotros remember to close information technology. A method like readlines() will piece of work okay for small files, but what if we have a more circuitous document? Using Python with statements will ensure that files are handled safely.
- The with argument is used for safely accessing resource files.
- Python creates a new context when it encounters the with cake.
- Once the block executes, Python automatically closes the file resource.
- The context has the same telescopic equally the with statement.
Permit'due south practice using the with argument by reading an email we have saved as a text file.
email.txt
Love Valued Customer,
Thank you for reaching out to u.s.a. nearly the issue with the product that you purchased. We are eager to accost whatsoever concerns you may have about our products.
We desire to make certain that you are completely satisfied with your purchase. To that terminate, nosotros offer a xxx-day, money-back guarantee on our entire inventory. Only return the product and we'll happily refund the price of your purchase.
Give thanks you,
The ABC Company
code example # open file with open("e-mail.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 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'south handler goes out of scope. When the office is finished with the file, with statement ensures the resource is handled responsibly.
Summary
Nosotros've covered several ways of reading files line by line in Python. We've learned there is a big difference between the readline() and readlines() methods, and that we can use a for loop to read the contents of a file object.
We also learned how to use the with statement to open and read files. Nosotros saw how the context director was created to brand handling files safer and easier in Python.
Several examples were provided to illustrated the various forms of file treatment available in Python. Accept time to explore the examples and don't be afraid to experiment with the code if you don't understand something.
If yous'd like to acquire well-nigh programming with Python, follow the links beneath to view more keen lessons from Python for Beginners.
Related Posts
- Using Python try except to handle errors
- How to use Python split string to ameliorate your coding skills
- Using Python cord chain for better readability
Recommended Python Grooming
Course: Python three For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.
Source: https://www.pythonforbeginners.com/files/4-ways-to-read-a-text-file-line-by-line-in-python
0 Response to "How to Read Text File Python as Lines"
Enregistrer un commentaire