我一直在用这段代码为我正在做的一个项目随机取学生的名字和成绩,但是当我只想取100个名字而不是1000个名字时,我写的文本文件就什么都没有了。你知道吗
from random import randint
file = open("rawgrade.txt", "w")
# Create the list of all the letters in the alphabet to easily select from
alphalist = []
for letter in "abcdefghijklmnopqrstuvwxyz":
alphalist.append(letter)
# Create random people and grades for the test file
for i in range(100): # only works for 1000 and up in my trials
# Create the random name of the person
namelen = randint(1, 16)
namestr = ""
for j in range(namelen):
randomletter = randint(0,25)
namestr += alphalist[randomletter]
# Create the random grade for the person
grade = randint(0, 100)
# Write to file
file.write(namestr + " " + str(grade) + "\n")
完成后需要关闭文件。否则结果是不可预测的:
(如果您正在repl或ipython中运行,则在退出之前,文件可能不会“关闭自身”。)
但是你的代码中还有很多其他非常非Pythonic的方面,我现在没有时间去看了!。。。简短示例:
alphalist
,因为你可以索引这个字符串。你知道吗with
打开和关闭为了好玩,以下是我认为更好的版本:
相关问题 更多 >
编程相关推荐