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



我已经尽了一切努力来实现这一点。我要做的是获取一个文件,为每一行分配一个变量,然后设置变量的类型。它在列表中读作[和'是一个行号,我不知道该怎么办。我在文件中也有需要保存的列表。我的错误是: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}

.readlines()函数返回一个列表,每个项都包含一行。为了从每一行中去掉换行符,您可以使用列表理解:

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

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

从文本文件中检索变量值的最佳方式?

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

对于列表,您可能需要一个函数来从字符串中提取列表。但是,如果您没有预料到安全漏洞,那么使用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()

最新更新