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

标签 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 语句?

最佳答案

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/

相关文章:

python - 融化后从 pandas 数据框中提取行作为列

Python - 在 Linux 上使用 cron 作业发送 KDE Knify 消息?

python - 为什么 Pillow 无法识别 JPEG 格式?

python - 从 numpy 求和二维数组创建加权 igraph 图作为邻接矩阵

python - Jython 何时支持 Python 3?

python-3.x - 加速 Keras LSTM

python - 无法访问位于目标元素之外的某些文本

python - 与 arduino 代码交互的 Pyserial 无法正常工作

python - 使用 python 如何为三元变量提供 0, 1 , 2 ?

python - 如何从 Windows 的回收站中删除文件? Python