[英]When appending lines from a text file into a list, it sets the whole line to a string. How do I recognise different data types inside a text file?
I am making a Pokémon game using Python 3.7.0 and I am making a save/load function using text documents.我正在使用 Python 3.7.0 制作 Pokémon 游戏,并且正在使用文本文档制作保存/加载功能。 Each line inside the text file holds a string and an integer and I was wondering if there was a way to recognise that those data types already exist and append them to the list while keeping the type.
文本文件中的每一行都包含一个字符串和一个整数,我想知道是否有办法识别这些数据类型已经存在并将它们附加到列表中,同时保留类型。
A sub issue that is cause by this is that each character in the index is treated as a separate index, rather than each part separated by the comma.由此导致的一个子问题是索引中的每个字符都被视为一个单独的索引,而不是每个部分用逗号分隔。
I've tried splitting each data type on a separate line and appending each one separately, then checking if it contains quotations or not but that just leaves me with the same result that I've been getting.我尝试将每种数据类型拆分为单独的一行并分别附加,然后检查它是否包含引号,但这只会让我得到与我得到的结果相同的结果。
Each line in the text files appears like this ('name',level):文本文件中的每一行显示如下('name',level):
'charmander',12
'bulbasaur',7
'squirtle',13
My code to load the file into a list is as follows:我将文件加载到列表中的代码如下:
path, dirs, files = next(os.walk("resources/saves")) # Read directory
fileCount = len(files)
while fileCount > 0:
for filename in os.listdir("resources/saves"): # Iterates directory
fileCount -= 1
loadFile = open("resources/saves/%s" % (filename),"r")
pokeCount = 6
for line in loadFile:
if pokeCount > 0:
party.append(line.split()) # Adds first six Pokémon to the party
pokeCount -= 1
else:
pc.append(line.split()) # Adds rest to the PC
print("Game loaded!")
After getting the output below, I tried:得到下面的输出后,我试过:
for i in party:
for j in i:
j.replace('\"','')
print(j) # Test if each part is treated as an index
However I got each character printed on a new line, as if each one was a new index, rather than the name and level be treated as two separate indexes.但是我将每个字符打印在新行上,就好像每个字符都是一个新索引,而不是将名称和级别视为两个单独的索引。
I expect the appended list to look like this:我希望附加列表如下所示:
[['charmander',12],['bulbasaur,7],['squirtle',13]]
However the list I get is:但是我得到的清单是:
[["'charmander','12'"],["'bulbasaur,'7'"],["'squirtle','13'"]]
The numbers are being treated as strings, then the whole index is being treated as a superior string.数字被视为字符串,然后整个索引被视为上级字符串。 I would like to have the name treated as a string in the first index of the sub-list, and the level treated as an integer in the second index of the sub-list.
我希望在子列表的第一个索引中将名称视为字符串,而在子列表的第二个索引中将级别视为整数。
Thanks to anyone who can understand this and who can help!感谢任何能理解这一点并能提供帮助的人!
You do not need to use a counter, simply check the length of the produces list - if it reaches 6 stop parsing the file.您不需要使用计数器,只需检查产品列表的长度 - 如果达到 6 则停止解析文件。
You need to split each line of your file at ,
and convert the level back to a number - you read strings from your file:您需要将文件的每一行拆分为
,
并将级别转换回数字 - 您从文件中读取字符串:
Create file:创建文件:
t = """
'charmander',12
'bulbasaur',7
'squirtle',13"""
Read and process file:读取和处理文件:
with open("data.txt","w") as f:
f.write(t)
pokemons = []
with open("data.txt") as f:
for line in f:
line = line.strip() # remove \n and other whitespaces
if line: # only process non empty lines
try:
poke, lvl = line.split(",")
except ValueError:
print("Unable to split line into 2 parts: ", line)
continue
try:
lvl = int(lvl) # convert to int
except ValueError:
print("Unable to convert lvl to number: ", lvl)
continue
poke = poke.strip("'") # get rid of the delimiting '
# add to list of pokemons when all was ok
pokemons.append( [poke,lvl] )
if len(pokemons) == 6:
break
print(pokemons)
Output:输出:
[['charmander', 12], ['bulbasaur', 7], ['squirtle', 13]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.