Question

I have two comma delimited text files with content as below:

File1:

TR,23456.23,H,56789

TR,54678.13,F,14567

TR,67889.12,R,89876

File2:

SG,6789.24,J,53452

SG,8909.25,F,56789

SG,5467.11,S,56783

I want to extract sentences from the first and second file and combine them in a new text file in just one line as below:

TR,54678.13,F,14567,SG,8909.25,F,56789

However, in my code, the result obtained is the following:

TR,54678.13,F,14567

,SG,8909.25,F,56789

Why the sentences from the second file are being written below the sentences from the first file?. I need both sentences to be combined on the same line. Does anybody know why is this happening and how could I solve the problem?.

This is my code:

contfil=0
direct=os.listdir(path1)
for file in direct:
  with open(os.path.join(save_path1,file),'r') as Textfile1:
    for eachline1 in Textfile1:
       for field in eachline1.split():
           ID1=field.split(',') [2]
           with open(os.path.join(save_path2,os.listdir(save_path2) [contfil]),'r') as Textfile2:
               for eachline2 in Textfile2:
                   for field in eachline2.split():
                        ID2=field.split(',') [2]
                        if ID2==ID1:
                           fo=open(os.path.join(save_path3,'Matched_Lines.txt'),'a')
                           fo.write('%s,%s\n' %(eachline1,eachline2))
                           fo.close()
  contfil+=1
Was it helpful?

Solution

All you need to do is strip each line. Change this line:

fo.write('%s,%s\n' %(eachline1,eachline2))

to this:

fo.write('%s,%s\n' %(eachline1.strip(),eachline2.strip()))

What's happening is that each line you read in has a newline (\n) at the end. When you print them out, that newline is output. strip removes the newline before outputting.

OTHER TIPS

You might want to try

combinedline = ' '.join([eachline1, eachline2])

and then

 fo.write('%s\n', % combinedline)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top