Question & Answer: python delete double white space between columns from txt file and save result in new file…..

python delete double white space between columns from txt file and save result in new file

I have txt file 1 has the following contents:

AW_003015.1     156   VPSELGGVGLKNTQYARLVEI
AS_010029.1     215       LASGETVAAFKLTEPSSGSDA
CE_010039.1     433   SEAAWKVTDEKIQIMGGMGFM
RN_000019.1     477      ILRLFVALQGKMDKGKELSGL
DP_020039.1     603      HPTAQHEKMLKDTWCIEAAAR

I want to make single line space between columns and save that in new txt file as following:

AW_003015.1 156 VPSELGGVGLKNTQYARLVEI
AS_010029.1 215 LASGETVAAFKLTEPSSGSDA
CE_010039.1 433 SEAAWKVTDEKIQIMGGMGFM
RN_000019.1 477 ILRLFVALQGKMDKGKELSGL
DP_020039.1 603 HPTAQHEKMLKDTWCIEAAAR

This is my code I did not be able to do that:

outfile = open(“file2.txt”, “w”) # Clears existing file, open for writing

with open(“file1.txt”) as infile:

for line in infile:

line = line.strip()

#print(line)

if line:

line = line.strip()

while ‘ ‘ in line:

line = line.replace(‘ ‘, ”)

print(line)

outfile.write(line)

Expert Answer

 

Still stressed from student homework?
Get quality assistance from academic writers!