I'm trying to compare multiple lists in Python. The idea is that we have multiple lists and are comparing each item in each list to a list of aggregated unique values. We then create an excel sheet where we would show each list side by side and any values missing from a particular list would show as PLACEHOLDER in that cell.
(I had a hard time explaining, but if you don't understand after reading please ask questions and I'll adjust the explanation accordingly )
filecount = 0
for file in files:
filecount += 1
with open(file) as file_object:
row = 0
for line in agg_Names:
#if line match, output to row
print (file_object)
if line in file_object.readlines():
worksheet.write(row, filecount, line)
row += 1
print ("found match")
The last if statement isn't right. It's supposed to compare each item in agg_Names to the current list and output the value. Currently, I'm only getting matches on the first row.
The reason why you're getting only a single line is because readlines()
returns all the lines of the file as a list and your comparison happens only once.
So, after your first iteration, file_object.readlines()
would be empty because the buffer ( file_object
) is empty.
You can modify your code to this,
filecount = 0
for file in files:
filecount += 1
with open(file) as file_object:
file_lines = file_object.readlines()
row = 0
for line in agg_Names:
#if line match, output to row
if line in file_lines:
worksheet.write(row, filecount, line)
row += 1
print ("found match")
Hope this helps.
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.