0
我必须创建一个从python中的文本文件读取随机行的函数。从文本文件中随机读取一行的函数
我有下面的代码,但我无法得到它的工作
import random
def randomLine(filename):
#Retrieve a random line from a file, reading through the file irrespective of the length
fh = open(filename.txt, "r")
lineNum = 0
it = ''
while 1:
aLine = fh.readline()
lineNum = lineNum + 1
if aLine != "":
# How likely is it that this is the last line of the file ?
if random.uniform(0,lineNum)<1:
it = aLine
else:
break
fh.close()
return it
print(randomLine(testfile.txt))
我走到这一步,但是,需要帮助走得更远,请帮
一旦程序运行我” m得到错误说
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
您目前遇到的错误或问题是什么? – OregonTrail 2014-10-06 02:55:18
什么是错误?请将堆栈跟踪粘贴到您的问题中。 – OregonTrail 2014-10-06 02:58:12
'print(randomLine(testfile.txt))'你需要''testfile.txt'周围的引号,以便它变成一个字符串。 – 2014-10-06 03:01:52