In my Python lab, I need to ask the user how many numbers to store; have them enter said numbers individually and store them in a file named numbers1.txt. Then again, repeat this process but store the numbers in a file named numbers2.txt. From there I had to write some code that would read a line from one file and a line from the other file, the 2 integers are multiplied together and their value is added to a variable called scalar_product which was initialized at 0. The code should stop when one of the files has reached end of file.
The code I have so far is as follows:
def main():
num = int(input("How many numbers would you like to store"))
numbers1 = open('numbers1.txt', 'w')
for count in range(1, num + 1):
nums = input("Enter each number individually {}:".format(count))
numbers1.write(str(nums) + "\n")
numbers1.close()
def main_two():
num2 = int(input("How many numbers would you like to store"))
numbers2 = open('numbers2.txt', 'w')
for count in range(1, num2 + 1):
nums2 = input("Enter each number individually {}:".format(count))
numbers2.write(str(nums2) + "\n")
numbers2.close()
main()
main_two()
numfile1 = open("numbers1.txt","r")
numfile2 = open("numbers2.txt","r")
scalar_product = 0
number1 = numfile1.readline()
number2 = numfile2.readline()
while number1 != "" and number2 != "":
scalar_product += int(number1) * int(number2)
number1 = numfile1.readline()
number2 = numfile2.readline()
numfile1.close()
numfile2.close()
I have no issues with the first few steps, Python prompts the users for the amount of numbers they would like to store but when I reach the section on multiplying the 2 values from numbers1.txt and numbers2.txt I get the following ValueError:
How many numbers would you like to store2
Enter each number individually 1:4
Enter each number individually 2:5
How many numbers would you like to store3
Enter each number individually 1:4
Enter each number individually 2:6
Enter each number individually 3:3
Traceback (most recent call last):
File "/Users/jake./PycharmProjects/CH9_Munyak_Jacob/ReadingProcessFiles.py", line 31, in <module>
number1 = numfile1.readline()
ValueError: I/O operation on closed file.
Process finished with exit code 1
Can anybody point me in the right direction?
I am not sure why It's a closed file when I re-opened it in line 24 and line 25