How to Read a .lst File in Python

Storing data in files lets you lot keep a record of the information with which a programme is working. This ways you don't accept to generate data over over again when working with a program. You just read that data from a file.

To read files, apply the readlines() method. Once you've read a file, you lot use split up() to turn those lines into a listing.

In this guide, nosotros discuss how to use the separate() method to read a text file into a list. We'll refer to an example so y'all can get started reading text files into lists speedily.

Python: Read Text File into List

Allow's start with a text file chosen grilled_cheese.txt. This file contains the ingredients for a grilled cheese sandwich. Our file content looks like this:

2 tbsp, ricotta ane tbsp, grated parmesan 50g, mozzarella 25g, gorgonzola ii, thick slices white bread 1 tbsp, butter

The first column in our file contains the quantity of each ingredient to exist used. The second column contains the name of an ingredient.

We read this file into our code using the open() and readlines() methods:

with open up("grilled_cheese.txt", "r") equally grilled_cheese: 	lines = grilled_cheese.readlines() 	print(lines)

In our lawmaking, we open a file called "grilled_cheese.txt" in read mode. Read manner is denoted past the "r" character in our open() argument. Side by side, we print those lines to the console.

Let's see what our Python code returns:

81% of participants stated they felt more confident nigh their tech job prospects after attending a bootcamp. Go matched to a bootcamp today.

The boilerplate bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their commencement job.

['2 tbsp, ricotta\due north', 'ane tbsp, grated parmesan\n', '50g, mozzarella\n', '25g, gorgonzola\n', 'two, thick slices white bread\north', 'i tbsp, butter\n']

Our lawmaking returns a list of each line in our file. This is not quite the output we are expecting. While we've read our file into a listing, nosotros take a problem: each line is stored in its ain string. Ingredients and their quantities are non separate.

Divide Values into a Listing

To solve this problem, we use the carve up() method. This method lets us split a string using a separator character we specify.

To start, we declare two lists: quantities and ingredients. This code will remain indented because it is part of our open() block of code.

            quantities = [] 	ingredients = []

We'll iterate over our list so we can admission each line of text from our file. So we'll dissever each line into two parts. The dividing betoken is the comma followed past a infinite on each line:

for l in lines: 		 as_list = l.split(", ") 		 quantities.append(as_list[0]) 		 ingredients.append(as_list[1])

The for loop lets us read our file line past line. The first value in "as_list" is the quantity of an ingredient. The second value is the name of the ingredient. We then impress both of these lists to the console:

            print(quantities) 	print(ingredients)

Let's run our lawmaking:

['2 tbsp, ricotta\n', '1 tbsp, grated parmesan\northward', '50g, mozzarella\n', '25g, gorgonzola\n', 'two, thick slices white breadstuff\n', 'one tbsp, butter\northward'] ['2 tbsp', '1 tbsp', '50g', '25g', '2', 'ane tbsp'] ['ricotta\northward', 'grated parmesan\north', 'mozzarella\northward', 'gorgonzola\n', 'thick slices white bread\north', 'butter\n']

Our code prints three lists to the console. The first listing is a list of all the lines of text in our file. The second list contains all the quantities from our file. The third list contains all the ingredients.

form-submission

Discover Your Bootcamp Match

  • Career Karma matches y'all with top tech bootcamps
  • Get exclusive scholarships and prep courses

Remove New Lines

There is all the same one improvement that we demand to make. Every ingredient ends in the "\due north" character. This character denotes a new line. We can remove this character by using the replace() method:

for fifty in lines: 	   	  as_list = l.split(", ") 		  quantities.append(as_list[0]) 		  ingredients.append(as_list[1].replace("\north", ""))

In our for loop, we supplant the value "\due north" with an empty string. We practice this on the as_list[1] value which correlates to the proper noun of each ingredient.

Now that we've made this change, our plan is set:

with open up("grilled_cheese.txt", "r") as grilled_cheese: 	   lines = grilled_cheese.readlines()  	   quantities = [] 	   ingredients = []  	   for l in lines: 	  			 as_list = fifty.split(", ") 			     quantities.append(as_list[0]) 			     ingredients.append(as_list[ane].replace("\northward", ""))  	   print(quantities) 	   print(ingredients)

Allow'southward run our code and see what happens:

['2 tbsp', '1 tbsp', '50g', '25g', '2', '1 tbsp'] ['ricotta', 'grated parmesan', 'mozzarella', 'gorgonzola', 'thick slices white bread', 'butter']

Our code successfully transforms our text file into two lists. One listing contains the quantities of ingredients for a recipe. The other list contains the ingredients nosotros'll apply for the recipe.

Conclusion

You lot can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain graphic symbol.

In the example above, we carve up a string into a list based on the position of a comma and a space (", "). Now yous're set to read a text file into a list in Python like an expert.

webbwassing.blogspot.com

Source: https://careerkarma.com/blog/python-read-text-file-into-list/

0 Response to "How to Read a .lst File in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel