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,
- Create a file, or open an existing file, use open(filename, mode) which returns a file handler.
- Read a file, use the filehandler.read(size) method where size is optional and which returns the data read as a string.
- Write to a file, use the filehandler.write(string) method which returns the number of characters written.
- 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()
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!