2

I want to write a program that read multiple files and processes them in one loop.

I want to search for the id in all files and take the mark of a student.

My code is:

iD = int(input("Enter the your ID: "))
mathFile = open ('COMP2101.txt','r')
itFile = open ('STAT1001.txt','r')
bioFile = open ('BIOL2101.txt','r')

for line in mathFile and itFile and bioFile:
    line = line.rstrip()
    part = line.split(" ")
    studentId = int(part[0])

    if studentId == iD:
        mathMark = part[1]
        print("math",mathMark)

    if studentId == iD:
        itMark = part[1]
        print("it",itMark)

    if studentId == iD:
        bioMark = part[1]
        print("lbio",bioMark)


mathFile.close()
itFile.close()
bioFile.close()

How can I map the file name to if statement?

3
  • You can merge all files to one map and then search it in map Commented Nov 20, 2017 at 12:08
  • can you please explain more. Because I try to use map function but does not work with me :( Commented Nov 20, 2017 at 12:11
  • Do you really need to do this with a single loop / for statement? If so, why? Commented Nov 20, 2017 at 12:14

2 Answers 2

3
from itertools import izip_longest # zip_longest in Python 3

with open('COMP2101.txt') as f1, open('STAT1001.txt') as f2, open('BIOL2101.txt') as f3:
    for line_f1, line_f2, line_f3 in izip_longest(f1, f2, f3, fillvalue=<anything you want>):
        # code

can you please tell me what is wrong in my code and how i can improve it?

Consider this demonstration in order to understand what's happening with your

for line in mathFile and itFile and bioFile:

loop:

>>> for x in [1,2] and [3,4] and [5,6]: print(x)
... 
5
6

because

>>> [1,2] and [3,4] and [5,6]
[5, 6]

How to improve it? Use my splendid answer, of course! :)

Sign up to request clarification or add additional context in comments.

5 Comments

can you please tel me what wrong in my cod and how i can to improve it ?
What about if i change and with coma , does it work ?
@prog no, it will not. What's wrong with the solution I gave you?
@prog good, trying to understand what went wrong is the right approach. If you are unsure whether something works, you don't need to ask me however. Just try it!
Thank you. I will try :)
1

Something like

filenames = {
    'Math': 'COMP2101.txt',
    'IT': 'STAT1001.txt',
    'Biology': 'BIOL2101.txt',
}
for subject, filename in filenames.items():
    with open(filename, 'r') as f:
        for line in f:
            line = line.rstrip()
            ...
            if studentId == iD:
                mark = part[1]
                print(subject, mark)

2 Comments

He wants to do it in single loop.
can you please tel me what wrong in my cod and how i can to improve it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.