Home > Software engineering >  How do I get an output of lines that comes as a result merging lines in 2 files line by line, then s
How do I get an output of lines that comes as a result merging lines in 2 files line by line, then s

Time:03-15

I have to take lines from 2 files, put them side by side and write them into a new text file.

File 1 "pythonStatements.txt":

    enter code hereprint("Hello World")       # print statement

   x = x   1      #Assignment statement 

  for i in range(1,n):    #for loop with range  

         calculateSum(a,b)   #function call

File 2 "machineCode.txt":

0000000000010100

1100110011001100

1010101010101010

1001001001001000

Write code that combines the 2 files line by line and the output should be in a new file.

My code:

mct = open("machineCode.txt", "r")
pst = open("pythonStatements.txt", "r")

for linex in pst:
    linex=linex.lstrip()
    linex=linex.rstrip()
    for liney in mct:
        x=open("NewFile","w")
        x.write("%s %s \n"%(linex,liney))

I am able to put the first lines of the 2 files side by side, and save the output in a third file, but the other lines are not showing for some reason. Can someone explain what I am doing wrong and what i can do to fix it?

Output in the third file should look like this:

print("Hello World")       # print statement 1001001001001000 

x = x   1      #Assignment statement 1001001001001000 

for i in range(1,n):    #for loop with range 1001001001001000 

calculateSum(a,b)   #function call 1001001001001000

NEW CODE:

mct = open("machineCode.txt", "r")
pst = open("pythonStatements.txt", "r")
x=open("output.txt","w")
​
for linex in pst:
    for liney in mct:
        print("")
    x.write("%s %s \n"%(linex.lstrip().rstrip(),liney))
​
mct.close()
pst.close()
x.close()

Ouput of the NEW CODE:

print("Hello World")       # print statement 1001001001001000 
x = x   1      #Assignment statement 1001001001001000 
for i in range(1,n):    #for loop with range 1001001001001000 
calculateSum(a,b)   #function call 1001001001001000 

DESIRED OUTPUT:

print("Hello World")     0000000000010100
x = x   1    1100110011001100
for i in range(1,n):     1010101010101010
calculateSum(a,b)    1001001001001000

CodePudding user response:

The problem was that you open file for rewriting every iteration in the loop.

with open("machineCode.txt") as mct:
    with open("pythonStatements.txt") as pst:
        with open("NewFile", "w") as new:
            for line_x, line_y in zip(mct, pst):
                new.write(line_x.strip()   line_y)

mct = open("machineCode.txt")
pst = open("pythonStatements.txt")
new = open("NewFile", "w")

while True:
    try:
        new.write(next(mct).strip()   next(pst))
    except StopIteration:
        break
        
mct.close()
pst.close()
new.close()
  • Related