Python reading lines in nested for loops from two files

人盡茶涼 提交于 2019-12-11 12:12:19

问题


I want to match the lines of one text file with another text file, line by line, there is a problem with my nested for loops, it must be simple, but I can't find it,

for line1 in ratings:
    cont1+=1

    for line2 in movies:
         cont2+=1
         print(cont1,cont2)

I simplified it with this loops, to check the error, The outer loop doesn't reach cont=2,

1 1
1 2
1 3
1 4
1 5
1 6
1 7
.
.
.
1 157
>>>

回答1:


you need to loop over both files simultaneously

ratings= open('ratings.txt')
movies= open('movies.txt')

for rating, movie in itertools.izip(ratings, movies):
    # do task

or

ratings= open('ratings.txt').readlines()
movies= open('movies.txt').readlines()

for rating, movie in zip(ratings, movies):
    # do task



回答2:


The problem is that I need to reset the inner loop with seek(0), doing that the loop works properly, thanks to everyone for your replies.




回答3:


Your implementation runs for every line in file1 run all line in file2,

the actual code shd be,

for line1,line2 in zip(ratings,movies):
 cont1+=1
 cont2+=1
 print(cont1,cont2)



回答4:


with open('ratings.txt') as ratings, open('movies.txt') as movies:
    for rating, movie in itertools.izip(ratings, movies):
        # do task

This is an improvement on avasal's answer in that it picks up the lines iteratively (equivalent to the old xreadlines that is now deprecated) rather than reading all the lines in via readlines(). So it should read a line from each, then process them, then read another line etc, permitting Files Of Enormity where readlines implementation would be limited to smaller files.

Note that izip continues until one of the iterators stops, so you'll only get as many rows as the shorter file. I'm assuming that's correct, however, since the code implicitly assumes the two files match anyway.



来源:https://stackoverflow.com/questions/13137969/python-reading-lines-in-nested-for-loops-from-two-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!