AnswerBun.com

How to load lines from a file into variables that can be either strings, floats, or ints?

Stack Overflow Asked by hamstercoding on January 5, 2022

I tried using int() and str() but it gave me an ValueError. I’m making a RPG where you can save and load your data using text files, and i want it to take data from a previous game (in a text file, already achieved) and set the variables from specific line numbers, so you get your previous data.

My code is:

f = open(name+".txt",'r')
enter = f.readline()
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]
f.close()

(I didn’t put in global because it would be too long.)
When I run this, I get an error saying the index is out of range. The code is on https://repl.it/@HamsterCoding/Screen-Testing#screen.py if you want to see it better.

2 Answers

You're getting an index out of bounds because readline() only reads the one line. You should use readlines() to get an array of all the lines in your text file.

File:

duck
1
c
1.2

Code:

f = open("duck.txt")
enter = f.readlines() # Changed from readline to readlines
y = enter[0].replace("n", "") # .replace replaces all newlines ("n") with empty strings
hp = enter[1].replace("n", "")
coins = enter[2].replace("n", "")
status = enter[3].replace("n", "")
print(enter)
print(y)
print(int(hp)) # cast str to int
print(coins)
print(float(status)) # cast str to float

Output:

['duckn', '1n', 'cn', '1.2']
duck
1 # int
c
1.2 # float

Answered by burntchowmein on January 5, 2022

Let's say you have the following txt-file:

1
word
2.5

The first issue you face is that the default type of the value from the text file is going to be string. Therefore, a classification of the content of the file would help you. The following piece of code will achieve this:

f = open('1.txt', 'r')
val_int = []
val_float = []
val_str = []
for i, line in enumerate(f):
    try:
        val = float(line)
        if val.is_integer():
            val_int.append((i,int(val)))
        else:
            val_float.append((i,val))
    except:
        val_str.append((i,line.replace('n','')))
f.close()
print(val_int) # OUTCOME: [(0, 1)]
print(val_float) # OUTCOME: [(2, 2.5)]
print(val_str) # OUTCOME: [(1,'word')]

The tuple to maintain the index of the line for future use.

Answered by Baraa on January 5, 2022

Add your own answers!

Related Questions

Python, change a var by a string

4  Asked on February 21, 2021 by beardlongo

   

Vue – how to show an array of data in a table?

2  Asked on February 21, 2021 by jayk23

     

CMake unit testing – Unresolved external symbol

1  Asked on February 21, 2021 by chrispytoes

   

Break string into new rows after grepl

2  Asked on February 21, 2021 by ip2018

   

Send unicode sms with java

3  Asked on February 21, 2021 by hong4rc

     

Getting n1 n2 outputs after conversion

2  Asked on February 21, 2021 by icemilo

   

Is that possible to make for each user table in database

0  Asked on February 21, 2021 by haddadi-abdraouf

     

Run-time Error 1004; Error handling

2  Asked on February 20, 2021 by karl-drews

       

Password Generating program in python

2  Asked on February 20, 2021 by m-ismail

         

Error TS1086:An accessor cannot be declared in an ambient context

0  Asked on February 20, 2021 by leonardokunkel

 

Pass object data as FormData

2  Asked on February 20, 2021 by swarup-chavan

   

Iteration in Python throws results no desired

1  Asked on February 20, 2021 by catalina-hernndez

         

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP