如何在python中循环多个文件并逐个处理它

时间:2017-11-20 12:07:28

标签: python python-3.x python-2.7

我想编写一个程序来读取多个文件并在一个循环中处理它们。

我想在所有文件中搜索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语句?

2 个答案:

答案 0 :(得分: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
  

你可以告诉我我的代码有什么问题以及如何改进它吗?

请考虑此演示,以了解您的

发生了什么
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]

如何改进?当然,请使用我的精彩答案! :)

答案 1 :(得分:0)

这样的东西
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)