Replace comma with a new line in a text file using Python

In this tutorial, we will learn how to replace the comma with a new line in a text file in Python.

Before proceeding to the solution, let us learn about dealing with text files in python first with a simple example:

Python provides in-built methods for file handling operations, such as open, read, write and close. To,

  1. Create a file, or open an existing file, use open(filename, mode) which returns a file handler.
  2. Read a file, use the filehandler.read(size) method where size is optional and which returns the data read as a string.
  3. Write to a file, use the filehandler.write(string) method which returns the number of characters written.
  4. Close a file, use the filehandler.close() method.

There are also various file modes such as r, w, r+, w+, a, etc. out of which the r is the default mode.

Syntax to open and read the file contents:

>>> fhr=open('filename.txt','r') 
>>> data=fh.read()
>>> fhr.close()

Syntax to open and write to the file:

>>> fhw=open('file.txt','w')
>>> fhw.write("Hello \n")
>>> fhw.close()

Program to replace the comma with a new line in a text file in Python

f1=open("Desktop/file1.txt","r+")
input=f1.read()
print(input)
input=input.replace(',','\n')
print(input)
f2=open("Desktop/file1.txt","w+")
f2.write(input)
f1.close()
f2.close()

Output:

HI,BYE,GO
HI
BYE
GO
9

This program starts by opening an existing text file in read mode and then the contents are stored in a variable and displayed. Then using the in-built method replace() for that variable, replace the comma with a newline. Write the updated variable contents onto the same text file. Finally, close all the file handlers used for reading and writing.

I hope this tutorial was helpful. Thanks for reading!

Recommended posts:
Introduction to file handling of python
How to find the longest line from a text file in Python

2 responses to “Replace comma with a new line in a text file using Python”

  1. Nellie says:

    Thanks, this was perfect for what I needed

  2. David says:

    I’m not sure that’ll be sufficient enough for what people searched for I understand you don’t have any say about what Google comes up with but at least you could tag it better… Just a suggestion! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *