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()
Output:
Thanks, this was perfect for what I needed
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! 😉