0
파이썬의 텍스트 파일에서 임의의 줄을 읽는 함수를 만들어야합니다.텍스트 파일에서 임의로 한 줄을 읽는 기능
나는 다음과 같은 코드를 가지고 있지만 얻을 수 아니다는
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))
을 일을 내가 지금까지 가지고 있지만, 프로그램은 내가 '실행되면
도와주세요, 더 갈 도움이 필요합니다 오류가 발생했습니다.
print(randomLine(testfile.txt))
NameError: name 'testfile' is not defined
현재 직면 한 오류 또는 문제는 무엇입니까? – OregonTrail
무엇이 오류입니까? 귀하의 질문에 스택 추적을 붙여주십시오. – OregonTrail
'print (randomLine (testfile.txt))''testfile.txt'는 따옴표가 필요하므로 문자열이됩니다. –