读两个输入文件

时间:2014-11-19 14:14:45

标签: python python-3.x input

我有以下问题陈述:

  

编写一个程序:

     
      
  1. 读取两个输入文件
  2.   
  3. 使用每个文件中包含的整数填充二维表
  4.   
  5. 检查两个表的大小,以确保它们具有相同的行数和列数。如果表格大小不同,则打印错误消息
  6.   
  7. 从每个文件中读取数据后,创建第三个表
  8.   
  9. 第三个表中的元素是第一个表中每个元素乘以第二个表中相应元素的结果:thirdTable [i] [j] = firstTable[i] [j] * secondTable[i] [j]
  10.   

到目前为止,我需要知道如何将第二个文件放入我的代码中。以及如何编写表三的代码。这是第一个输入文件的代码:

def main():
    print("Table One")
    (row, column, table) = readInput()
    return()


def readInput():
    table = []
    inputFile = open("Table 1.txt", "r")

     #  Read the first line containing the number of rows and columns
    line = inputFile.readline()

    #  split the line into two strings
    (row, column) = line.split()

    #  convert the strings into integers
    row = int(row)
    column = int(column)

    #  loop on the file container, reading each line

    for line in inputFile :
        line = line.rstrip()  #strip off the newline 
        dataList = line.split()  #  split the string into a list 
        table.append(dataList)

 #  Loop through the table and convert each element to an integer


    for i in range(row):
        for j in range (column):
            table[i] [j] = int(table[i] [j])  # convert the string to an integer
            print(" %3d" % (table[i] [j]), end = " ")
        print()

    inputFile.close()  #  close the file
    return(row, column, table)  #  return the number of rows and columns


main()    

1 个答案:

答案 0 :(得分:2)

您可以让readInput函数采用参数:

def readInput(filename):
    #         ^^^^^^^^ Change it here 
    table = []
    inputFile = open(filename, "r")
    #       and here ^^^^^^^^

    ... # Rest of your function

然后从main使用它:

def main():

    row1, column1, table1 = readInput('Table1.txt')

    row2, column2, table2 = readInput('Table2.txt')