如何为多个输入文件运行相同的python代码

如何为多个输入文件运行相同的python代码,python,loops,input,Python,Loops,Input,我有两个输出文件,其中包含相同的数据,但值不同。我使用以下Python代码读取它们并返回所需的数据/值: upper = input("Enter file name (upper): ") lower = input("Enter file name (lower): ") fhr = open(upper) for line in fhr: word = line.rstrip().split() if len(word) >

我有两个输出文件,其中包含相同的数据,但值不同。我使用以下Python代码读取它们并返回所需的数据/值:

upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")

fhr = open(upper)
for line in fhr:
    word = line.rstrip().split()
    if len(word) > 1 and word[1] == '1:47':
        try:
            sabs = word[2]
        except:
            continue
        tot_upper = float(sabs)
        print('Total upper:', tot_upper)
fhr.close()

fhr = open(lower)
for line in fhr:
    word = line.rstrip().split()
    if len(word) > 1 and word[1] == '1:47':
        try:
            sabs = word[2]
        except:
            continue
        tot_lower = float(sabs)
        print('Total lower:', tot_lower)
fhr.close()
这给了我输出:

Total upper: x
Total lower: y
有没有办法简化代码,打开第一个文件,运行代码,然后循环回到开头,打开第二个文件,运行相同的代码?大概是这样的:

upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")

file = [upper, lower]

for inp in file:
    fhr = open(file)
    for line in fhr:
        word = line.rstrip().split()
        if len(word) > 1 and word[1] == '1:47':
            try:
                sabs = word[2]
            except:
                continue
            if inp == upper:
                tot_upper = float(sabs)
                print('Total upper:', tot_upper)
            elif inp == lower:
                tot_lower = float(sabs)
                print('Total lower:', tot_lower
    fhr.close()
我仍然想要相同的输出:

Total upper: x
Total lower: y

您可能需要使用以下函数:

upper = input("Enter file name (upper): ")
lower = input("Enter file name (lower): ")

def f(name, s): # idk what is the function for so change to a custom name
    fhr = open(name)
    for line in fhr:
        word = line.rstrip().split()
        if len(word) > 1 and word[1] == '1:47':
            try:
                sabs = word[2]
            except:
                continue
            tot = float(sabs)
            print(f'Total {s}:', tot)
    fhr.close()

f(upper, 'upper')
f(lower, 'lower')
您可以这样做:

for label in 'upper', 'lower':
   # Ask for filename, using the label.
   # Process the file.
   # Print the result, using the label.

谢谢,这真是太棒了!当代码采用这种形式时,我是否可以将这些值相加或相减?例如,diff=upper-lower您可能希望使用return将值返回给调用者。如果您不熟悉函数及其参数和返回语句,请参考您选择的Python教程。我无法回答,因为我不明白函数将返回什么?所有总值之和?函数返回单个值,例如上限=850.5,下限=800.5。我需要从str转换为float,但我能做上下=50.0吗?