最近在写代码时,出现了一个Bug,折腾了很长一段时间。主要功能是实现从文件中任意取10条数据。代码如下:
with open('file.txt','r') as fil:
data = []
for _ in range(10):
randn = np.random.randint(0,19999)#文件大小共20000条数据
search_data = fil.readlines()[randn]
data.append(search_data)
运行时,报错,错误为:list index out of range。正确代码为:
data=[]
for _ in range(10):
randn = np.random.randint(0,19999)
with open('file.txt','r') as fil:
search_data = fil.readlines()[randn]
data.append(search_data)
总结一下:这可能是读取文件机制造成的原因;可以同时打开一个文件10次进行读取;而不能直接对其进行10次随机取值。