9

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.

4
  • What if you have spaces in the "fields" as it were... ? Commented Feb 20, 2019 at 11:43
  • I can but i am learning python and it is a requirement of the project that there should be no tabs or whitespaces etc Commented Feb 20, 2019 at 11:50
  • Okay, where are you at for this project... have you been able to read a tab delimited file in? Commented Feb 20, 2019 at 11:52
  • Do you mean can i read this file in python? Yes i can do that. But i can't figure out how to remove the TAB yet Commented Feb 20, 2019 at 11:54

2 Answers 2

10

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()
Sign up to request clarification or add additional context in comments.

4 Comments

any reason you're not using a with statement here for opening the files?
It doesn't seem to work. It copies the entire thing from input file and pastes into the output file
@Shameendra, I have updated the answer check it again
@mooga Works perfectly. Thanks a lot. However i would like to suggest putting the indent in the for loop so beginners don't make a mistake
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.