【发布时间】:2019-07-31 16:28:13
【问题描述】:
是否可以让 python 随机选择一行,除了文件的第一行,它是为其他东西保留的?任何帮助表示赞赏:)
with open(filename + '.txt') as f:
lines = f.readlines()
answer = random.choice(lines)
print(answer)
【问题讨论】:
标签: python
是否可以让 python 随机选择一行,除了文件的第一行,它是为其他东西保留的?任何帮助表示赞赏:)
with open(filename + '.txt') as f:
lines = f.readlines()
answer = random.choice(lines)
print(answer)
【问题讨论】:
标签: python
对数组进行切片:
answer = random.choice(lines[1:])
【讨论】:
您也可以提前保留第一行,随意使用随机选择:
with open(filename + '.txt') as f:
reserved_line = next(f) # reserved for something else
lines = f.readlines()
answer = random.choice(lines)
【讨论】:
reserved_line = lines[0](至少这样更易读)。
lines list 将存储多余的第一行,应在进一步的潜在切片中跳过(条件可能会有所不同)
next,则使用lines = list(f)读取剩余的行;不要将迭代与直接文件访问混为一谈。
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)
由于文件是它自己的迭代器,因此无需直接调用readline 或readlines。您可以直接将文件传递给list,使用itertools.islice 跳过第一行。
from itertools import islice
with open(filename + '.txt') as f:
lines = list(islice(f, 1, None))
answer = random.choice(lines)
【讨论】: