Reading From a Txt File and Making a Dictionary in Python

Python is one of the most popular programming languages in the world. One reason for its popularity is that Python makes it like shooting fish in a barrel to work with data.

Reading data from a text file is a routine task in Python. In this post, we're going to look at the fastest mode to read and dissever a text file using Python. Splitting the data will convert the text to a listing, making information technology easier to work with.

We'll likewise encompass some other methods for splitting text files in Python, and explain how and when these methods are useful.

In the following examples, we'll meet how Python can assist us principal reading text data. Taking advantage of Python's many built-in functions will simplify our tasks.

Introducing the split() method

The fastest way to split up text in Python is with the split up() method. This is a born method that is useful for separating a string into its individual parts.

The split() method volition return a list of the elements in a string. Past default, Python uses whitespace to split the cord, only you can provide a delimiter and specify what character(due south) to employ instead.

For example, a comma(,) is frequently used to divide string information. This is the case with Comma Separated Value (CSV) files. Any you choose as the separator, Python volition use to dissever the cord.

Splitting text file with the split() method

In our first example, we have a text file of employee data, including the names of employees, their phone numbers, and occupations.

Nosotros'll need to write a Python program that can read this randomly generated information and split the information into lists.

employee_data.txt
Lana Anderson 485-3094-88 Electrician
Elian Johnston 751-5845-87 Interior Designer
Henry Johnston 777-6561-52 Astronomer
Dale Johnston 248-1843-09 Journalist
Luke Owens 341-7471-63 Teacher
Amy Perry 494-3532-17 Electrician
Chloe Baker 588-7165-01 Interior Designer

Afterwards using a Python with statement to open the information file, we can iterate through the file's contents with a for loop. Once the data is read, the split() method is used to separate the text into words.

In our case, the text is separated using whitespace, which is the default behavior of the split() method.

Example one: Splitting employee data with Python

            with open("employee_data.txt",'r') every bit data_file:     for line in data_file:         data = line.split()         impress(information)                      

Output

            ['Lana', 'Anderson', '485-3094-88', 'Electrician'] ['Elian', 'Johnston', '751-5845-87', 'Interior', 'Designer'] ['Henry', 'Johnston', '777-6561-52', 'Astronomer'] ['Dale', 'Johnston', '248-1843-09', 'Announcer'] ['Luke', 'Owens', '341-7471-63', 'Teacher'] ['Amy', 'Perry', '494-3532-17', 'Electrician'] ['Chloe', 'Baker', '588-7165-01', 'Interior', 'Designer']                      

Splitting strings with a comma

We provide an optional separator to the split() method to specify which character to split up the string with. The default delimiter is whitespace.

In the next instance, we'll use a comma to dissever test score information read from a file.

grades.txt
Janet,100,50,69
Thomas,99,76,100
Kate,102,78,65

Example 2: Splitting grades with a comma

            with open("grades.txt",'r') equally file:     for line in file:         grade_data = line.strip().split(',')         print(grade_data)                      

The strip() method is used here to remove the newline graphic symbol (\north) from the end of the lines.

Output

            ['Janet', '100', '50', '69'] ['Thomas', '99', '76', '100'] ['Kate', '102', '78', '65']                      

Splitting a text file with splitlines()

The splitlines() method is used to become a listing of the lines in a text file. For the next examples, we'll pretend we run a website that'due south dedicated to a theatre visitor. We're reading script information from text files and pushing it to the visitor's website.

juliet.txt
O Romeo, Romeo, wherefore art thou Romeo?
Deny thy father and refuse thy proper noun.
Or if thou wilt not, be but sworn my love
And I'll no longer be a Capulet.

Nosotros tin read the file and split the lines into a list with the splitlines() method. Later, a for loop tin be used to impress the contents of the text data.

Example three: Using splitlines() to read a text file

            with open("juliet.txt",'r') as script:     oral communication = script.read().splitlines()  for line in speech:     print(line)                      

Using a Generator to Divide a Text File

In Python, a generator is a special routine that can exist used to create an array. A generator is like to a function that returns an array, simply it does then one chemical element at a time.

Generators use the yield keyword. When Python encounters a yield statement, it stores the country of the office until subsequently, when the generator is called over again.

In the side by side example, we'll use a generator to read the beginning of Romeo'due south famous speech from Shakespeare's Romeo and Juliet. Using the yield keyword ensures that the land of our while loop is saved during each iteration. This tin exist useful when working with big files.

romeo.txt
But soft, what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and stake with grief
That thou, her maid, art far more fair than she.

Case 4: Splitting a text file with a generator

            def generator_read(file_name):     file = open(file_name,'r')     while True:         line = file.readline()         if not line:             file.shut()             intermission         yield line  file_data = generator_read("romeo.txt") for line in file_data:     print(line.split())                      

Reading File Data with List Comprehension

Python list comprehension provides an elegant solution for working with lists. We can take advantage of shorter syntax to write our lawmaking with list comprehension. In add-on, listing comprehension statements are ordinarily easier to read.

In our previous examples, we've had to apply a for loop to read the text files. Nosotros can exchange our for loop for a single line of code using list comprehension.

List Comprehension Syntax:
my_list = [expression for element in list]

Once the data has been obtained via list comprehension, nosotros use the dissever() method to separate the lines and add them to a new list.

Using the same romeo.txt file from the previous instance, let'southward encounter how listing comprehension can provide a more elegant approach to splitting a text file in Python.

Example 5: Using listing comprehension to read file data

            with open("romeo.txt",'r') equally file:     lines = [line.strip() for line in file]  for line in lines:     print(line.split())                      

Split a Text File into Multiple Smaller Files

What if nosotros have a large file that we'd similar to split into smaller files? We split a big file in Python using for loops and slicing.

With list slicing, nosotros tell Python we want to work with a specific range of elements from a given list. This is done by providing a showtime point and end point for the slice.

In Python, a list can be sliced using a colon. In the following example, we'll use list slicing to split a text file into multiple smaller files.

Carve up a File with Listing Slicing

A listing can be split up using Python listing slicing. To do then, we outset read the file using the readlines() method. Adjacent, the height half of the file is written to a new file called romeo_A.txt. We'll use list slicing within this for loop to write the get-go half of the original file to a new file.

Using a second for loop, we'll write the residual of the text to some other file. In order to perform the slice, nosotros demand the len() method to find the total number of lines in the original file.

Lastly, the int() method is used to convert the result of the division to an integer value.

Instance half-dozen: Splitting a single text file into multiple text files

            with open("romeo.txt",'r') every bit file:     lines = file.readlines()  with open("romeo_A.txt",'w') as file:     for line in lines[:int(len(lines)/two)]:         file.write(line)  with open up("romeo_B.txt",'w') as file:     for line in lines[int(len(lines)/ii):]:         file.write(line)                      

Running this program in the same directory every bit romeo.txt will create the post-obit text files.

romeo_A.txt
But soft, what lite through yonder window breaks?
It is the due east, and Juliet is the sun.

romeo_B.txt
Arise, fair lord's day, and kill the envious moon,
Who is already sick and pale with grief
That 1000, her maid, art far more off-white than she.

Related Posts

We've seen how to use the split() method to carve up a text file. Additionally, our examples have shown how dissever() is used in tandem with Python generators and listing comprehension to read big files more elegantly.

Taking advantage of Python's many built-in methods, such as carve up() and readlines(), allows usa to process text files more than quickly. Using these tools will save united states fourth dimension and try.

If you're serious well-nigh mastering Python, it'due south a good idea to invest some time in learning how to use these methods to prepare your own solutions.

If you'd like to learn more virtually programming with Python, delight visit the following tutorials from Python for Beginners.

  • How a Python comment tin make or break your program
  • Turbo charge your code with Python list comprehension

Recommended Python Grooming

Course: Python 3 For Beginners

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

tobinobsomed.blogspot.com

Source: https://www.pythonforbeginners.com/files/the-fastest-way-to-split-a-text-file-using-python

0 Response to "Reading From a Txt File and Making a Dictionary in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel