从文件python中生成列表

时间:2015-12-14 14:04:39

标签: python list file random

我有一个看起来像这样的文件:就像这样

Pokemon     HP  Attack_Points   Type    Weakness
Bulbasaur   45     49     Grass Fire
Ivysaur     60     62     Grass Fire
Venusaur    80     82     Grass Fire

我试图从随机行生成列表,这是我的代码:

from random import randint

open_pokedex=open("pokedex.txt","r")
p1_p1=list()
pokemon_selection=(randint(1,40))
p1_p1.append(open_pokedex.readline()[pokemon_selection])

但这不起作用任何人都有任何想法? 输出:这次生成31并显示p1_p1,因为这是[' \ t']

问题解决了

但是bcs的坏txt文件它会这样做[' Charmander \ t39 \ t52 \ tFire \ tWater \ n']如何删除这些标签而不会弄乱文件本身

1 个答案:

答案 0 :(得分:3)

使用linecache.getline。它完全符合你的要求;从文件中获取行lineno

import linecache
from random import randint

pokemon_selection = randint(1, 40)
pokemon = linecache.getline("pokedex.txt", pokemon_selection)