[英]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? 是否有可能使python随机选择文件保留第一行以外的第一行? Any help appreciated :)
任何帮助表示赞赏:)
with open(filename + '.txt') as f:
lines = f.readlines()
answer = random.choice(lines)
print(answer)
切片数组:
answer = random.choice(lines[1:])
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 else
lines = f.readlines()
answer = random.choice(lines)
f.readlines()
doesn't read every line from a file; f.readlines()
不会从文件中读取每一行; 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. 但是,由于文件是其自己的迭代器,因此无需直接调用
readline
或readlines
。 You can instead simply pass the file to list
, using itertools.islice
to skip the first line. 您可以直接使用
itertools.islice
将文件传递到list
,以跳过第一行。
from itertools import islice
with open(filename + '.txt') as f:
lines = list(islice(f, 1, None))
answer = random.choice(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.