Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file.
Replace Comma With a New Line in a Text File
Below are the possible approaches to replacing a comma with a new line in a text file.
- Using replace Method
- Using split and join
- Using List Comprehension and join
file.txt
It contains well written, well thought and well explained computer science and programming articles.
The portal has a vast library of articles, tutorials, and problem sets.
Replace a Comma With a New Line in a Text File Using the replace Method
In this example, we are using the replace method to replace commas with new lines in the file's content. The replace method allows us to specify the characters we want to replace and the replacement string.
with open('file.txt', 'r') as file:
content = file.read()
content = content.replace(',', '\n')
with open('output.txt', 'w') as file:
file.write(content)
Output:
output.txt
It contains well written
well thought and well explained computer science and programming articles.
The portal has a vast library of articles
tutorials
and problem sets.
Replace Comma With a New Line in a Text File Using split and join
In this example, we use the split method to split the content based on commas, then join the elements with new lines using the join method. This approach uses string manipulation to achieve the desired result.
with open('file.txt', 'r') as file:
content = file.read()
content = '\n'.join(content.split(','))
with open('output.txt', 'w') as file:
file.write(content)
Output:
It contains well written
well thought and well explained computer science and programming articles.
The portal has a vast library of articles
tutorials
and problem sets.
Replace Comma With a New Line in a Text File Using List Comprehension and join
Here, we use list comprehension to iterate through each line and replace commas with new lines. Then we write the modified lines back to the file. This approach is simple and efficient for handling line-by-line modifications.
with open('file.txt', 'r') as file:
lines = [line.replace(',', '\n') for line in file]
with open('output.txt', 'w') as file:
file.writelines(lines)
Output:
It contains well written
well thought and well explained computer science and programming articles.
The portal has a vast library of articles
tutorials
and problem sets.