Example 6: Splitting a single text file into multiple text files
If we have a large file and viewing all the data in a single file is difficult, we can split the data into multiple files. let’s see an example where we split file data into two files.
Python list slicing can be used to split a list. To begin, we read the file with the readlines() method. The file’s first-half/upper half is then copied to a new file called first half.txt. Within this for loop, we’ll use list slicing to write the first half of the main file to a new file.
A second loop is used to write the other part of the data into a second file. The second half of the data is contained in the second half.txt. To perform the slice, we need to use the len() method to determine the count of lines in the main file Finally, the int() method is used to convert the division result to an integer value
Python3
# opening the main file with open ( "examplefile.txt" , 'r' ) as file : data = file .readlines() # writing half of the data in one file with open ( "first_half.txt" , 'w' ) as file1: for line in data[: int ( len (data) / 2 )]: file1.write(line) # writing another half of the data in one file with open ( "second_half.txt" , 'w' ) as file2: for line in data[ int ( len (data) / 2 ):]: file2.write(line) |
Output:
How to Split a File into a List in Python
In this article, we are going to see how to Split a File into a List in Python.
When we want each line of the file to be listed at consecutive positions where each line becomes an element in the file, the splitlines() or rstrip() method is used to split a file into a list. Let’s see a few examples to see how it’s done.
Contact Us