theFile = open('theFile', 'r+')
fileCheck = open('fileCheck', 'r+')
numOfFiles = 3
currentNum = 0
def check():
for i in theFile:
for lines in fileCheck:
if i == lines:
print("We already have " + i)
break
else:
print("We don't have " + i)
break
check()
fileCheck.close()
theFile.close()
fileCheck contents are:
line 1
line 2
line 4
line 5
theFile contents are:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
I am trying to loop through both files to check if the contents from theFile
are in fileCheck
. For example, if "line 1"
is already in fileCheck
, I want it to ignore that and keep moving. When it gets to "line 3"
which is not in fileCheck
, I want it to do a series of code, then when it gets to "line 4"
it should skip it and "line 5"
, too. From line 6-10 it performs the code I tell it to do. I know this is not working because there are only 4 lines in fileCheck
so it only performs that loop 4 times, and doesn't get all 10 lines. I want it to loop through all 10 lines but I can't figure out how.
Here
for i in theFile:
for lines in fileCheck:
...
it looks like you're trying to iterate over fileCheck more than once. In that case, you will have to reset it somehow (for example, repeat the
fileCheck = open('fileCheck', 'r+')
but you could start by reading the whole file at once:
fileCheck = list(open('fileCheck', 'r+')
Have you considered doing
theFile = set(open('theFile, 'r+'))
fileCheck = set(open('fileCheck', 'r+'))
and then using set differences: theFile - fileCheck
are the lines that are in the first but not the second set; line in theFile
is True or False, and so on.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.