2016-10-19 4 views
1

random.randint를 사용하여 난수를 생성 한 다음 그 수를 변수에 할당합니다.txt 파일의 임의의 줄을 인쇄 하시겠습니까?

f = open(filename. txt) 
lines = f.readlines() 

rand_line = random. randint(1,10) 
print lines[rand_line] 
+2

파일에 몇 줄이 있습니까? (또는 오히려, 얼마나 많은 요소가'lines' 목록에 있습니다) – UnholySheep

+1

시도해보십시오. randint (0, len (lines)) –

+0

@ A.Kot 여전히 잘못 될 수 있습니다. –

답변

6

당신은 random.choice

를 사용하려면 : 나는 시도 무엇 여기

list index out of range

: 그럼 내가 변수에 할당 된 번호로 선을 인쇄 할,하지만 난 오류가 계속

import random 
with open(filename) as f: 
    lines = f.readlines() 
    print(random.choice(lines)) 
0

이 코드는 open 함수에 문자열을 전달하려는 것으로 가정하고, 점 뒤에 공백이없는 것으로 가정하면 ... 그러나주의하십시오 파이썬에서의 인덱싱, 즉 0에서 시작하지 않고 1에서 시작하여 len(your_list)-1에서 끝납니다.

random.choice이 더 사용하지만, 당신이 당신의 아이디어를 따라하려는 경우 오히려 것 : randint 이후

import random 
with open('name.txt') as f: 
    lines = f.readlines() 
    random_int = random.randint(0,len(lines)-1) 
    print lines[random_int] 

모두 경계를 포함, 당신은 len(lines)-1까지보고해야합니다.

0
f = open(filename. txt) 
lines = f.readlines() 

rand_line = random.randint(0, (len(lines) - 1)) # https://docs.python.org/2/library/random.html#random.randint 
print lines[rand_line] 
관련 문제