简体   繁体   English

如何从列表(txt 文件)中读取字符串并将它们打印为整数、字符串和浮点数?

[英]How to get read strings from a list(a txt file) and print them out as ints, strings, and floats?

I've tried literally everything to make this work.我已经尝试了一切来完成这项工作。 What i'm trying to do is take a file, assign each line a variable, and then set the type of the variable.我要做的是获取一个文件,为每一行分配一个变量,然后设置变量的类型。 It's reading it in the list as [ and ' being a line number, and I don't know what to do.它在列表中将其读取为 [ 和 ' 是行号,我不知道该怎么做。 I also have lists inside of the file that I need to save.我在文件中也有需要保存的列表。 My error is: ValueError: invalid literal for int() for base 10: '['我的错误是: ValueError: invalid literal for int() for base 10: '['

My code is:我的代码是:

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}

I think its better if you read the file this way, which first reads and removes whitespace and then splits into lines.我认为如果您以这种方式读取文件会更好,它首先读取并删除空格,然后拆分为行。 Then you can set a variable to each line (also you need to set the result of changing variable types to the variable).然后您可以为每一行设置一个变量(您还需要将更改变量类型的结果设置为变量)。

For lists, you may need a function to extract the list from the string.对于列表,您可能需要 function 从字符串中提取列表。 However if you aren't expecting security breaches then using eval() should be fine.但是,如果您没有预料到安全漏洞,那么使用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()

The .readlines() function returns a list, each item containing a separate line. .readlines() function 返回一个列表,每个项目包含一个单独的行。 In order to strip the newline from each of the lines, you can use a list comprehension:为了从每一行中删除换行符,您可以使用列表推导:

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

You can then proceed to cast each item in the list separately, as you have, or try to somehow automatically infer the type in a loop.然后,您可以像您一样继续分别转换列表中的每个项目,或者尝试以某种方式自动推断循环中的类型。 This would be easier if you formatted the example file more like a configuration file.如果您将示例文件格式化为更像配置文件,这将更容易。 This thread has some relevant answers:这个线程有一些相关的答案:

Best way to retrieve variable values from a text file? 从文本文件中检索变量值的最佳方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Python Pandas读取.txt文件-字符串和浮点数 - Read .txt file with Python Pandas - strings and floats 如何遍历字符串列表并识别整数和浮点数,然后将它们添加到列表中? - How do I iterate over a list of strings and identify ints and floats and then add them to a list? 如何将txt中的浮点数作为字符串从Python列表中取出 - How to take floats from a txt to a Python list as strings 如何将浮点数从txt转换为Python列表作为字符串来回答问题? - How to take floats from a txt to a Python list as strings to answer questions? 如何将由整数和浮点数组成的列表中的字符串列表转换为整数和浮点数? - How do I convert a list of strings in a list composed of ints and floats to both ints and floats? 将文件中的浮点数和字符串读入数据类型完整的元组列表中 - Read floats and strings from a file into a list of tuples with data types intact python将列表中的字符串转换为int和float - python converting strings in list to ints and floats 如何将文件中的行加载到可以是字符串、浮点数或整数的变量中? - How to load lines from a file into variables that can be either strings, floats, or ints? 从文件到字典以浮点数而不是字符串的形式读取 - Read from file to dictionary as floats instead of strings 如何编写字符串和整数列表以有效归档 - How to write a list of strings and ints to file efficiently
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM