随机数文件写入器
说明:
- 写一个程序,把一系列随机数字写入一个文件。
- 每个随机数字的范围应该在1到100之间。
- 这个应用程序应该让用户指定文件中要包含多少个随机数字。
这是我目前的代码:
import random
afile = open("Random.txt", "w" )
for line in afile:
for i in range(input('How many random numbers?: ')):
line = random.randint(1, 100)
afile.write(line)
print(line)
afile.close()
print("\nReading the file now." )
afile = open("Random.txt", "r")
print(afile.read())
afile.close()
我遇到了一些问题:
文件中写入的随机数字没有按照用户设定的范围来。
文件打开后无法关闭。
读取文件时,什么都没有。
虽然我觉得设置还不错,但似乎在执行时总是卡住。
2 个回答
0
import random
ff=open("file.txt","w+")
for _ in range(100):
ff.write(str(random.randrange(500,2000)))
ff.write("\n")
ff.seek(0,0)``
while True:
aa=ff.readline()
if not aa:
print("End")
break
else:
if int(aa)%2==0:
print(int(aa))
ff.close()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
7
把 for line in afile:
这一行去掉,然后把里面的内容拿出来。另外,因为在Python 3中,input
返回的是字符串,所以你需要先把它转换成 int
类型。你现在是想把一个整数写入文件,但其实你应该写的是字符串。
这段代码应该是这样的:
afile = open("Random.txt", "w" )
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
afile.close()
如果你担心用户输入的不是整数,可以使用 try/except
结构来处理这个问题。
afile = open("Random.txt", "w" )
try:
for i in range(int(input('How many random numbers?: '))):
line = str(random.randint(1, 100))
afile.write(line)
print(line)
except ValueError:
# error handling
afile.close()
你之前想做的是遍历 afile
中的每一行,但实际上没有任何行,所以什么都没发生。