Splitting lines in a text file or a string is a common task in Python programming. In this tutorial, we will learn how to split lines in Python using different methods. These methods come in handy when you are trying to clean or preprocess your text data for further analysis.
Step 1: Split lines using the split() function
The split() function is one of the easiest ways to split a string or a text file. By default, it splits lines based on the whitespace, but you can also use a custom delimiter as an argument.
Here’s an example:
1 2 3 |
text = "Hello, world!\nWelcome to the Python tutorial!" lines = text.split('\n') print(lines) |
The output will be:
['Hello, world!', 'Welcome to the Python tutorial!']
This method works well when you have a string and want to split it into multiple lines.
Step 2: Use the readlines() method for text files
If you have a text file and would like to split its lines, you can use the readlines() method. This method reads the entire file into memory and splits it into lines automatically.
Here’s an example:
Create a file named “example.txt” with the following content:
Hello, world!
Welcome to the Python tutorial!
Python code:
1 2 3 |
with open("example.txt", "r") as file: lines = file.readlines() print(lines) |
The output will be:
['Hello, world!\n', 'Welcome to the Python tutorial!\n']
This method works well when you want to split lines in a text file.
Step 3: Use a loop to read lines one by one
If you have a large text file that cannot fit into memory, you can use a loop to read lines one by one without loading the entire file into memory.
Python code:
1 2 3 4 5 6 |
lines = [] with open("example.txt", "r") as file: for line in file: lines.append(line.strip()) print(lines) |
The output will be:
['Hello, world!', 'Welcome to the Python tutorial!']
Here we used strip() to remove the newline character from each line.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Method 1: Using split() function text = "Hello, world!\nWelcome to the Python tutorial!" lines = text.split('\n') print(lines) # Method 2: Using readlines() method for text files with open("example.txt", "r") as file: lines = file.readlines() print(lines) # Method 3: Using a loop to read lines one by one lines = [] with open("example.txt", "r") as file: for line in file: lines.append(line.strip()) print(lines) |
Output
['Hello, world!', 'Welcome to the Python tutorial!'] ['Hello, world!\n', 'Welcome to the Python tutorial!'] ['Hello, world!', 'Welcome to the Python tutorial!']
Conclusion
In this tutorial, we learned how to split lines in Python using different methods. You can use the split() function to split a string, readlines() method to split lines in a text file, or a loop to read lines one by one. These methods are essential when working with text data in Python programming.