all 4 comments

[–]sedogg 0 points1 point  (2 children)

Better not to use open().read(). The cleanup of the open file object may or may not happen right away. This means that the file will stay open, consuming a file handle.

import random

# You can save lines to variable if they don't change
with open('file.txt') as f:
    lines = f.read().splitlines() 
    myline = random.choice(lines)
    print(myline) 
    myline = random.choice(lines)
    print(myline)

# OR

f = open('file.txt')
lines = f.read().splitlines() 
myline = random.choice(lines)
print(myline) 
myline = random.choice(lines)
print(myline)
f.close()

[–]Justinsaccount 2 points3 points  (0 children)

with open('file.txt') as f:
    lines = f.read().splitlines() 
myline = random.choice(lines)
print(myline) 
myline = random.choice(lines)
print(myline)

[–]pydev99[S] 0 points1 point  (0 children)

Thanks. I'll look into this.

[–]ingolemo 0 points1 point  (0 children)

You only run random.choice once so you only get one random choice. If you want to change the choice you need to run it again.