如何从列表(txt文件)中获取读取的字符串,并将其打印为int、strings和float?

2024-05-16 10:16:49 发布

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

我已经尽了一切努力让这一切顺利。我要做的是获取一个文件,为每行分配一个变量,然后设置变量的类型。它在列表中读作[和',作为行号,我不知道该怎么做。我还需要保存文件中的列表。 我的错误是: ValueError: invalid literal for int() for base 10: '['

我的代码是:

def load_data():
f = open(name+".txt",'r')
enter = str(f.readlines()).rstrip('\n)
print(enter)
y = enter[0]
hp = enter[1]
coins = enter[2]
status = enter[3]
y2 = enter[4]
y3 = enter[5]
energy = enter[6]
stamina = enter[7]
item1 = enter[8]
item2 = enter[9]
item3 = enter[10]
equipped = enter[11]
firstime = enter[12]
armorpoint1 = enter[13]
armorpoint2 = enter[14]
armorpoints = enter[15]
upgradepoint1 = enter[16]
upgradepoint2 = enter[17]
firstime3 = enter[18]
firstime4 = enter[19]
part2 = enter[20]
receptionist = enter[21]
unlocklist = enter[22]
armorlist = enter[23]
heal1 = enter[24]
heal2 = enter[25]
heal3 = enter[26]
unlocked = enter[27]
unlocked2 = enter[28]
float(int(y))
int(hp)
int(coins)
str(status)
float(int(y2))
float(int(y3))
int(energy)
int(stamina)
str(item1)
str(item2)
str(item3)
str(equipped)
int(firstime)
int(armorpoint1)
int(armorpoint2)
int(armorpoints)
int(upgradepoint1)
int(upgradepoint2)
int(firstime3)
int(firstime4)
list(unlocklist)
list(armorlist)
int(heal1)
int(heal2)
int(heal3)
f.close()
SAMPLE FILE:
35.0
110
140
Sharpshooter
31.5
33
11
13
Slimer Gun
empty
empty
Protective Clothes
0
3
15
0
3
15
0
1
False
False
['Slime Slicer', 'Slimer Gun']
['Casual Clothes', 'Protective clothes']
4
3
-1
{'Protective Clothes': True}
{'Slimer Gun': True}

Tags: 文件列表forstatusfloatinthpenter
2条回答

我认为这样读文件更好,首先读取并删除空白,然后分成几行。然后,您可以为每一行设置一个变量(还需要将更改变量类型的结果设置为该变量)

对于列表,您可能需要一个函数来从字符串中提取列表。但是,如果您不希望出现安全漏洞,那么使用eval()就可以了

def load_data():
    f = open(name+".txt",'r')
    content = f.read().rstrip()
    lines = content.split("\n")

    y = float(int(enter[0]))
    hp = int(enter[1])
    coins = int(enter[2])
    status = enter[3]
    # (etc)

    unlocklist = eval(enter[22])
    armorlist = eval(enter[23])

    f.close()

函数返回一个列表,每个项目包含一个单独的行。要从每一行中删除换行符,可以使用列表:

f = open("data.txt", "r")
lines = [line.strip() for line in f.readlines()]

然后,您可以继续单独强制转换列表中的每个项目,或者尝试以某种方式自动推断循环中的类型。如果将示例文件的格式设置为更像配置文件,这将更容易。此线程有一些相关的答案:

Best way to retrieve variable values from a text file?

相关问题 更多 >