我一直在使用这段代码为我正在从事的项目随机生成学生的姓名和成绩,但是当我只想生成 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")
最佳答案
完成后您需要关闭文件。否则结果是不可预测的:
file.close()
(如果您在 repl 或 ipython 中运行,那么在您退出之前该文件可能不会“自行关闭”。)
但是您的代码还有很多其他非常非 Python 的方面,我现在没有时间详细讨论!...一个简短的示例:
- 不要使用“file”作为名称,因为它已经是内置名称。
- 不必费心制作
alphalist
,因为您可以为字符串建立索引。 - 使用
with
打开和关闭
为了好玩,这是我认为更好的版本:
from random import randint, choice
from string import ascii_lowercase
num_students = 100
max_name_len = 16
with open("rawgrade.txt", "w") as fil:
# Create random people and grades for the test file
for i in range(num_students):
# Create the random name of the person
### this can probably be made simpler....
namelen = randint(1, max_name_len)
namestr = ''.join([choice(ascii_lowercase) for j in range(namelen)])
# Create the random grade for the person
grade = randint(0, 100)
# Write to file
fil.write(namestr + " " + str(grade) + "\n")
关于python - 我有一段代码只适用于大于 1000 的数字。有解释为什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28829086/