Shameendra
Shameendra

Reputation: 182

Replace Tab with space in entire text file python

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.

Upvotes: 9

Views: 27597

Answers (2)

ChrisZZ
ChrisZZ

Reputation: 2141

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()

Upvotes: 1

mooga
mooga

Reputation: 3307

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()

Upvotes: 10

Related Questions