我想编写一个程序来读取多个文件并在一个循环中处理它们。
我想在所有文件中搜索该id并获取学生的分数。
我的代码是:
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()
如何将文件名映射到 if
语句?
最佳答案
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?
请考虑此演示,以便了解您的情况
for line in mathFile and itFile and bioFile:
循环:
>>> for x in [1,2] and [3,4] and [5,6]: print(x)
...
5
6
因为
>>> [1,2] and [3,4] and [5,6]
[5, 6]
如何改进?当然,请使用我精彩的答案! :)
关于python - 如何在python中循环多个文件并逐一处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47391673/