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