Like others said, you should close your files after using them, it's good practice:
with open("filepath/file.txt", "r") as file1:
some code here...
this automatically closes the file for you when the 'some code here' bit is done..
Here's one way to get the names and info out of the files.. using the re module(regular expressions)
t1 = [i.split() for i in list1] #test this out in the interpreter if you don't know
t2 = [i.split() for i in list2] #what it does
r = []
for i in t1:
for j in t2:
if i[0] == j[0]:
r.append('name: %s - grades: %s %s' % (i[0], ' '.join(i[1:]), ' '.join(j[1:])))
This will produce output like:
['name: nameb - grades: 50 60 77 88 34 88.9',
'name: namek - grades: 33 55 76 45 22 65.9',
'name: namem - grades: 22 43 65 87 42 77.6',
'name: Garry - grades: 44 65 87 90 86 66.9',
'name: Brian - grades: 54 07 67 08 77 32.88']
You could obviously format it differently
The full function:
def compare_files():
files = ["file1", "file2"]
file_list = []
for file in files:
with open("filepath/%s.txt", % file "r") as f:
file_list.append(f.readlines())
text1 = [i.split() for i in file_list[0]]
text2 = [i.split() for i in file_list[1]]
r = []
for i in text1:
for j in text2:
if i[0] == j[0]:
r.append('name: %s - grades: %s %s' % (i[0], ' '.join(i[1:]), ' '.join(j[1:])))
#if file f3 doesn't exist this will create it
with open("filepath/file3.txt", "w") as f3:
for line in r:
f3.write(i + '\n')
ioffile1.txtis identical to lineioffile2.txt?with ... assyntax.