Skip to content Skip to sidebar Skip to footer

How Do I Make Python Choose Randomly One Line After The First Line Of A File?

Is it possible to make python to randomly choose a line EXCEPT the first line of the file which is reserved for something else? Any help appreciated :) with open(filename + '.txt')

Solution 1:

Slice the array:

answer = random.choice(lines[1:])

Solution 2:

You may also reserve the 1st line beforehand and freely use random selection:

with open(filename + '.txt') as f:
    reserved_line = next(f)   # reserved for something elselines = f.readlines()
    answer = random.choice(lines)

Solution 3:

f.readlines() doesn't read every line from a file; it reads the remaining lines starting with the current file position.

with open(filename + '.txt') as f:        
    f.readline()  # read but discard the first line     
    lines = f.readlines()  # read the rest
    answer = random.choice(lines) 
    print(answer)

Since a file is its own iterator, though, there is no need to call readline or readlines directly. You can instead simply pass the file to list, using itertools.islice to skip the first line.

from itertools import islice

withopen(filename + '.txt') as f:
    lines = list(islice(f, 1, None))
    answer = random.choice(lines)

Post a Comment for "How Do I Make Python Choose Randomly One Line After The First Line Of A File?"