Python Txt File Again After Splitting

Python is ane of the virtually pop programming languages in the world. I reason for its popularity is that Python makes it easy to work with data.

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

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

In the post-obit examples, nosotros'll see how Python can help united states master reading text data. Taking advantage of Python'south many born functions will simplify our tasks.

Introducing the split() method

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

The split up() method will render a list of the elements in a string. Past default, Python uses whitespace to split the string, but you can provide a delimiter and specify what character(due south) to use instead.

For example, a comma(,) is often used to dissever string data. This is the case with Comma Separated Value (CSV) files. Whatever you choose equally the separator, Python volition apply to split the string.

Splitting text file with the divide() method

In our first example, we take 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 data 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 Instructor
Amy Perry 494-3532-17 Electrician
Chloe Baker 588-7165-01 Interior Designer

Later using a Python with statement to open up the data file, nosotros can iterate through the file'due south contents with a for loop. Once the information is read, the divide() method is used to dissever the text into words.

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

Example 1: Splitting employee data with Python

            with open("employee_data.txt",'r') equally data_file:     for line in data_file:         data = line.split()         print(data)                      

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', 'Bakery', '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 the string with. The default delimiter is whitespace.

In the next example, we'll use a comma to carve up test score data read from a file.

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

Example 2: Splitting grades with a comma

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

The strip() method is used here to remove the newline character (\n) 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 get a list of the lines in a text file. For the next examples, nosotros'll pretend we run a website that'south defended to a theatre company. We're reading script information from text files and pushing it to the company'south website.

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

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

Instance 3: Using splitlines() to read a text file

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

Using a Generator to Divide a Text File

In Python, a generator is a special routine that can be used to create an assortment. A generator is like to a role that returns an array, but it does so one element at a time.

Generators employ the yield keyword. When Python encounters a yield argument, it stores the country of the function until after, when the generator is chosen once more.

In the next example, we'll use a generator to read the beginning of Romeo's 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 can be useful when working with large files.

romeo.txt
But soft, what lite 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 pale with grief
That thou, her maid, art far more than off-white than she.

Example 4: Splitting a text file with a generator

            def generator_read(file_name):     file = open(file_name,'r')     while Truthful:         line = file.readline()         if not line:             file.close()             break         yield line  file_data = generator_read("romeo.txt") for line in file_data:     impress(line.split())                      

Reading File Information with List Comprehension

Python list comprehension provides an elegant solution for working with lists. We tin can take reward of shorter syntax to write our code with list comprehension. In addition, listing comprehension statements are usually easier to read.

In our previous examples, nosotros've had to use a for loop to read the text files. We can substitution our for loop for a single line of code using listing comprehension.

Listing Comprehension Syntax:
my_list = [expression for element in listing]

Once the data has been obtained via list comprehension, we use the carve up() method to dissever the lines and add them to a new listing.

Using the same romeo.txt file from the previous example, let's see how list comprehension can provide a more elegant arroyo to splitting a text file in Python.

Instance 5: Using list comprehension to read file data

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

Split a Text File into Multiple Smaller Files

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

With list slicing, we tell Python we want to work with a specific range of elements from a given list. This is done by providing a starting time betoken and end signal for the piece.

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

Separate a File with List Slicing

A list can be carve up using Python list slicing. To exercise so, we first read the file using the readlines() method. Next, the tiptop 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 commencement one-half of the original file to a new file.

Using a 2d for loop, nosotros'll write the residual of the text to another file. In order to perform the slice, nosotros need the len() method to find the total number of lines in the original file.

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

Instance vi: Splitting a unmarried text file into multiple text files

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

Running this program in the aforementioned directory every bit romeo.txt will create the following text files.

romeo_A.txt
Only soft, what light through yonder window breaks?
It is the east, and Juliet is the sun.

romeo_B.txt
Arise, off-white sun, and kill the envious moon,
Who is already sick and pale with grief
That thou, her maid, art far more off-white than she.

Related Posts

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

Taking reward of Python's many built-in methods, such as dissever() and readlines(), allows united states to procedure text files more quickly. Using these tools volition save us time and effort.

If yous're serious nigh mastering Python, it's a good idea to invest some time in learning how to employ these methods to prepare your ain solutions.

If you'd similar to larn more than about programming with Python, please visit the following tutorials from Python for Beginners.

  • How a Python annotate tin can brand or break your program
  • Turbo charge your lawmaking with Python list comprehension

Recommended Python Grooming

Course: Python iii For Beginners

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

scullfroff1994.blogspot.com

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

0 Response to "Python Txt File Again After Splitting"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel