2014-11-19 4 views
0

У меня есть следующая проблема заявление:Чтение два входных файлов

Write a program that:

  1. Reads two inputs files
  2. Populates a two dimensional table with the integers contained in each file
  3. Check the size of the two tables to make sure they both have the same number of rows and columns. If the tables are not the same size print an error message
  4. Once you have read the data from each file create a third table
  5. The elements in the third table are the result of multiplying each element in the first table by the corresponding element in the second table: thirdTable [i] [j] = firstTable[i] [j] * secondTable[i] [j]

Мне нужно знать, как поставить второй файл с моим кодом так far.And, как писать код для таблицы три. Вот код для первого входного файла:

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()  
+0

Является ли это Python? Добавьте тег языка. –

+0

@YuHao это python – lindsay

+1

'с открытым (file1) как f1, open (file2) как f2:' приходит на ум. Использование с блоками для обработки IO в основном предпочтительнее –

ответ

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

. Нужно ли мне изменить остальную часть моего кода или оставить его одинаковым? – lindsay

+0

@niya Думаю, вам нужно только изменить строку с помощью 'open' и определения функции. – parchment

+0

Я получил этот комментарий: Traceback (последний последний звонок): Файл «C: \ Program Files (x86) \ Wing IDE 101 5.0 \ src \ debug \ tserver \ _sandbox.py", строка 42, в Файл " C: \ Program Files (x86) \ Wing IDE 101 5.0 \ src \ debug \ tserver \ _sandbox.py ", строка 3, в основном pass builtins.TypeError: readInput() принимает 0 позиционных аргументов, но 1 дано – lindsay