import random
def main():
random1 = random.randrange(10,21,1)
create_file(random1)
process_file()
def create_file( random1):
generate = open('random_numbers.txt','w')
for x in range(random1):
random2 = random.randrange(1,101,1)
generate.write(str(random2)+'/n')
generate.close()
def process_file():
generate = open('random_numbers.txt','r')
entries = 0
total = 0
for x in generate:
entries += 1
integer = int(x)
total = integer + total
mean= sum/entries
print("There are",(entries),"entries in the file.")
print("The sum total of all the entries is ",(total))
print("The average of all the entries is ", format((mean),'.2f'))
main()
这一直给我这个错误,我不明白为什么整数值不起作用。我尝试将integer=int(x)
缩减为integer = x
,但之后我无法将x用作整数,这本身就是一个问题
Traceback (most recent call last):
File "U:\john oconnor lab 6.2.py", line 41, in <module>
main()
File "U:\john oconnor lab 6.2.py", line 20, in main
process_file()
File "U:\john oconnor lab 6.2.py", line 35, in process_file
number = int(x)
ValueError: invalid literal for int() with base 10: '29/n59/n17/n2/n8/n14/n2/n14/n9/n21/n5/n25/n15/n47/n'
答案 0 :(得分:3)
<iframe width="854" height="480" src="https://www.youtube.com/embed/cPVgwz5aN1o" frameborder="0" allowfullscreen></iframe>
你是不是想在那里写一个换行符?你的转义序列错了。
generate.write(str(random2)+'/n')
这应该解决generate.write(str(random2)+'\n')
中的问题,因为“random_numbers.txt”现在将用各自的行分隔的数字填充,而不是用斜杠和字母N分隔的数字。
此外,这一行:
process_file
应使用变量mean= sum/entries
而不是内置函数total
。
sum
答案 1 :(得分:0)
执行此操作for x in generate:
时,您的文件的每一行都会得到。因此,如您所知,文件的每一行都是'15 \ n'或'67 \ n'。
你应该这样做:
for x in generate:
entries += 1
x = x.strip()
integer = int(x)
total = integer + total
mean= sum/entries
x.strip()
将消除每行的'\ n'一词。
还要注意'\ n'和'/ n'
之间的区别