【问题标题】:How to run the same python code for multiple input files如何为多个输入文件运行相同的python代码
【发布时间】:2021-04-19 11:58:50
【问题描述】:

我有两个包含相同数据(但值不同)的输出文件。我正在使用以下 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

【问题讨论】:

    标签: python loops input


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      你可能需要使用函数:

      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')
      

      【讨论】:

      • 谢谢,这很好用!当代码采用这种形式时,我是否可以将这些值相加或相减?例如,diff = 上 - 下
      • 您可能希望使用return 将值返回给调用者。如果您不熟悉函数(及其参数和return 语句),请查阅您选择的 Python 教程。
      • 我无法真正回答,因为我不明白函数会返回什么?所有总值的总和?
      • 该函数返回单个值,例如上 = 850.5,下 = 800.5。我需要从 str 转换为 float 但我可以做上 - 下 = 50.0 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多