如何使python在文件的第一行之后随机选择一行?

2024-04-26 21:20:47 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能让python随机选择一行,除了文件的第一行是为其他内容保留的?感谢您的帮助:)

with open(filename + '.txt') as f:        
    lines = f.readlines()         
    answer = random.choice(lines) 
    print(answer)

Tags: 文件answertxt内容aswithrandomopen
3条回答

切片阵列:

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

f.readlines()不会从文件中读取每一行;它从当前文件位置开始读取剩余的行。你知道吗

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)

但是,由于文件是自己的迭代器,因此不需要直接调用readlinereadlines。您只需将文件传递给list,使用itertools.islice跳过第一行即可。你知道吗

from itertools import islice

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

您也可以预先保留第一行并自由使用随机选择:

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

相关问题 更多 >