Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Tab with space in entire text file python

Tags:

python-3.x

I have a text file which contains TAB between values and looks like this:

Yellow_Hat_Person    293    997    328    1031
Yellow_Hat_Person    292    998    326    1032
Yellow_Hat_Person    290    997    324    1030
Yellow_Hat_Person    288    997    321    1028
Yellow_Hat_Person    286    995    319    1026

I want to replace all the tabs with just a single space. so it looks like this:

Yellow_Hat_Person 293 997 328 1031
Yellow_Hat_Person 292 998 326 1032
Yellow_Hat_Person 290 997 324 1030
Yellow_Hat_Person 288 997 321 1028
Yellow_Hat_Person 286 995 319 1026

Any suggestions would be of help.

like image 259
Shameendra Avatar asked Feb 20 '19 11:02

Shameendra


2 Answers

You need to replace every '\t' to ' '

inputFile = open(“textfile.text”, “r”) 
exportFile = open(“textfile.txt”, “w”)
for line in inputFile:
   new_line = line.replace('\t', ' ')
   exportFile.write(new_line) 

inputFile.close()
exportFile.close()
like image 165
mooga Avatar answered Oct 12 '22 14:10

mooga


It would be better to use correct quote chars, and don't make input & output file names very similar. Based on @mooga's answer, please use this:

fin = open("input.txt", "r") 
fout = open("output.txt", "w")
for line in fin:
   new_line = line.replace('\t', ' ')
   fout.write(new_line) 

fin.close()
fout.close()
like image 31
ChrisZZ Avatar answered Oct 12 '22 15:10

ChrisZZ