我对Python很新,并且我正在为一个类做一个程序的问题。 main()和create_file工作,但是当它到达read_file时,解释器就在那里。程序正在运行,但一切都没有发生。
答案可能很简单,但我看不出来。提前感谢您的帮助。
我正在使用IDLE(Python和IDLE v.3.5.2)
以下是代码:
import random
FILENAME = "randomNumbers.txt"
def create_file(userNum):
#Create and open the randomNumbers.txt file
randomOutput = open(FILENAME, 'w')
#Generate random numbers and write them to the file
for num in range(userNum):
num = random.randint(1, 500)
randomOutput.write(str(num) + '\n')
#Confirm data written
print("Data written to file.")
#Close the file
randomOutput.close()
def read_file():
#Open the random number file
randomInput = open(FILENAME, 'r')
#Declare variables
entry = randomInput.readline()
count = 0
total = 0
#Check for eof, read in data, and add it
while entry != '':
num = int(entry)
total += num
count += 1
#Print the total and the number of random numbers
print("The total is:", total)
print("The number of random numbers generated and added is:", count)
#Close the file
randomInput.close()
def main():
#Get user data
numGenerate = int(input("Enter the number of random numbers to generate: "))
#Call create_file function
create_file(numGenerate)
#Call read_file function
read_file()
main()
答案 0 :(得分:6)
你在函数中有一个无限while
循环,因为entry
在循环期间永远不会改变。
处理文件中所有行的Pythonic方法如下:
for entry in randomInput:
num = int(entry)
total += num
count += 1