I do this:

f = open(sys.argv[1] ) ff = open(sys.argv[2] ) for line in f: for line2 in ff: print line,line2 

but it only prints the first line from the file f, although if you deduce it separately, it prints all the lines.

For example, in the file f there are lines:

 12 123 

and in the ff file line 1234, you need to output as follows:

 12 1234 123 1234 

in my case it outputs:

 12 1234 

does not take into account the second and subsequent lines.

    2 answers 2

    The open function returns an iterator over a file that returns, one by one, from one to another. After the iterator has reached the end of the file, it is completely exhausted and cannot be reused.

    This is what happens in your case. ff turned out to be exhausted at the first pass, with each subsequent pass it is empty and the internal cycle is no longer processed at all.

    The solution is to create an iterator already inside the loop, so that it is updated each time.

     f = open(sys.argv[1] ) for line in f: ff = open(sys.argv[2] ) for line2 in ff: print line,line2 

      There is no need for a cycle. As answered earlier, iterators are used here. Work with the file as with the object being iterated

       with open("textfile1") as textfile1, open("textfile2") as textfile2: for x, y in zip(textfile1, textfile2): x = x.strip() y = y.strip() print("{0}\t{1}".format(x, y)) 

      After calling the contents of the iterator, it becomes inaccessible. Save its value to a variable in order to pass into a nested loop, or use the lambda function to pass if its state is not required to be saved.

      You can read more about working with iterators from M. Lutz’s book, Learning Python.