python文件的生成列表

2024-09-28 14:19:13 发布

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

我有一个文件看起来像这样:它完全像这样

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\u p1为this=['\t']

问题已解决

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


Tags: 文件txttypeopenfirepointshpgrass
1条回答
网友
1楼 · 发布于 2024-09-28 14:19:13

使用^{}。它做的正是您想要的;从文件中获取行lineno。你知道吗

import linecache
from random import randint

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

相关问题 更多 >