How to Split a File into a List in Python
Last Updated :
22 Jun, 2022
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.
The file is opened using the open() method where the first argument is the file path and the second argument is a string(mode) which can be ‘r’ ,’w’ etc.. which specifies if data is to be read from the file or written into the file. Here as we’re reading the file mode is ‘r’. the read() method reads the data from the file which is stored in the variable file_data. splitlines() method splits the data into lines and returns a list object. After printing out the list, the file is closed using the close() method.
Create a text file with the name “examplefile.txt” as shown in the below image which is used as an input.
Python3
file_obj = open ( "examplefile.txt" , "r" )
file_data = file_obj.read()
lines = file_data.splitlines()
print (lines)
file_obj.close()
|
Output:
['This is line 1,', 'This is line 2,', 'This is line 3,']
Example 2: Using the rstrip()
In this example instead of using the splitlines() method rstrip() method is used. rstrip() method removes trailing characters. the trailing character given in this example is ‘\n’ which is the newline. for loop and strip() methods are used to split the file into a list of lines. The file is closed at the end.
Python3
file_obj = open ( "examplefile.txt" , "r" )
lines = [[x.rstrip( '\n' )] for x in file_obj]
print (lines)
file_obj.close()
|
Output:
[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
Example 3: Using split()
We can use a for loop to iterate through the contents of the data file after opening it with Python’s ‘with’ statement. After reading the data, the split() method is used to split the text into words. The split() method by default separates text using whitespace.
Python3
with open ( "examplefile.txt" , 'r' ) as file_data:
for line in file_data:
data = line.split()
print (data)
|
Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
Example 4: Splitting a text file with a generator
A generator in Python is a special trick that can be used to generate an array. A generator, like a function, returns an array one item at a time. The yield keyword is used by generators. When Python encounters a yield statement, it saves the function’s state until the generator is called again later. The yield keyword guarantees that the state of our while loop is saved between iterations. When dealing with large files, this can be useful
Python3
def generator_data(name):
file = open (name, 'r' )
while True :
line = file .readline()
if not line:
file .close()
break
yield line
data = generator_data( "examplefile.txt" )
for line in data:
print (line.split())
|
Output:
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
Example 5: Using list comprehension
Python list comprehension is a beautiful way to work with lists. list comprehensions are powerful and they have shorter syntax. Furthermore, list comprehension statements are generally easier to read.
To read the text files in previous examples, we had to use a for loop. Using list comprehension, we can replace ours for loop with a single line of code.
After obtaining the data through list comprehension, the split() is used to separate the lines and append them to a new list. let’s see an example to understand.
Python3
with open ( "examplefile.txt" , 'r' ) as file :
data = [line.strip() for line in file ]
print (data)
for line in data:
print (line.split())
|
Output:
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
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
with open ( "examplefile.txt" , 'r' ) as file :
data = file .readlines()
with open ( "first_half.txt" , 'w' ) as file1:
for line in data[: int ( len (data) / 2 )]:
file1.write(line)
with open ( "second_half.txt" , 'w' ) as file2:
for line in data[ int ( len (data) / 2 ):]:
file2.write(line)
|
Output:

Similar Reads
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variab
2 min read
Python | Split given list and insert in excel file
Given a list containing Names and Addresses consecutively, the task is to split these two elements at a time and insert it into excel. We can use a very popular library for data analysis, Pandas. Using pandas we can easily manipulate the columns and simply insert the filtered elements into excel fil
1 min read
How to split a Python list into evenly sized chunks
Iteration in Python is repeating a set of statements until a certain condition is met. This is usually done using a for loop or a while loop. There are several ways to split a Python list into evenly sized-chunks. Here are the 5 main methods: Method 1: Using a Loop with List SlicingUse for loop alon
3 min read
How to Create a List of N-Lists in Python
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers
3 min read
How to search and replace text in a file in Python ?
In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing text without using any external module Let see how we can search and replace text in a text file. First, we create a text file in which we want to search and replace text. Let this file b
5 min read
How to Get First N Items from a List in Python
Accessing elements in a list has many types and variations. This article discusses ways to fetch the first N elements of the list. Using List Slicing to Get First N Items from a Python ListThis problem can be performed in 1 line rather than using a loop using the list-slicing functionality provided
4 min read
How To Read .Data Files In Python?
Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
4 min read
How to Find the Longest Line from a Text File in Python
Finding the longest line from a text file consists of comparing the lengths of each line to determine which one is the longest. This can be done efficiently using various methods in Python. In this article, we will explore three different approaches to Finding the Longest Line from a Text File in Py
3 min read
Break a List into Chunks of Size N in Python
The task is to split the list into smaller sublists (chunks) where each sublist has at most N elements. For Example: For list = [1, 2, 3, 4, 5] and N = 2, the output should be [[1, 2], [3, 4], [5]]. Using List Comprehension We can use list comprehension to slice the list into chunks of size N. This
4 min read