-2

My codes are listed as following:

import time
f = open("q1", "r")
g = open("q2", "r")

f1 = (f)
f2 =(g)


for y in f1:
  for x in f2:
     print(y)
     sleep(1)
  print(x)

The output does not print line by line,but prints the whole file. How to print both files line by line?

output

1
2
3
4
5
a
b
c
d
e

desired output


1
a
2
b
3
c
4
d
5
e

  • What your code is saying is: "for every line in f, print all the lines in g". Which of course can't happen because the first time through `g` it is exhausted and won't print anything next time. – quamrana Nov 05 '22 at 12:46
  • 1
    Does it answer the question? [Reading a File Line by Line in Python](https://stackoverflow.com/questions/53283718/reading-a-file-line-by-line-in-python) – Giuseppe La Gualano Nov 05 '22 at 12:47
  • 1
    Does this answer your question? [Reading two text files line by line simultaneously](https://stackoverflow.com/questions/11295171/reading-two-text-files-line-by-line-simultaneously) – Javad Nov 05 '22 at 12:50
  • I'm not sure that the code you posted will give the output you listed. – quamrana Nov 05 '22 at 12:51

1 Answers1

0

You meant to iterate through both files at the same time which is what zip() gives you:

for y,x in zip(f1, f2):
    print(y)
    print(x)
quamrana
  • 37,849
  • 12
  • 53
  • 71