Python Forum
How do I convert this string back to a list of integers?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I convert this string back to a list of integers?
#1
Let's say I have this list where val1, etc are all integers such as val1 = 1, val2 = 15, val3 = 240

values = [val1, val2, val3] so now values = [1, 15, 240]

And I store it to a file named values.txt by using write(str(values)) and then I read it like values = read('values.txt')
and then print it it looks like this [1, 15, 240] which is what I would expect.

Now here is where I'm having trouble. How do I convert this string that was stored back into an actual list of integers that I can index each number?

Do I need to store it a different way? I know I could index each element of the list and store each element as a separate file but that isn't really what I want. I'm coding for use in a MicroPython project but testing it first using Python 3.7 in Thonny.

Thanks.
Don

I think I found a solution in the MicroPython forum. Storing the data as binary rather than text. Delete this post if you like. Thanks.
Reply
#2
an easy way i think is:

str = ""
for i in values:
str += str(i)
Reply
#3
please, show real code, don't explain what you have or what you expect. As of now it's not clear neither what you have, or what you want.
From what i get - the way you write is not correct (i.e. you will get also square brackets in the file).
For reading csv file - look at csv module or read the line and split at ','.
Note in any case you will need to convert each element to int, because they will come as str from the file.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(Apr-05-2020, 05:36 PM)buran Wrote: please, show real code, don't explain what you have or what you expect. As of now it's not clear neither what you have, or what you want.
From what i get - the way you write is not correct (i.e. you will get also square brackets in the file).
For reading csv file - look at csv module or read the line and split at ','.
Note in any case you will need to convert each element to int, because they will come as str from the file.

Thanks. I understand the importance of using code quotations and will do so from now on. Yes I did get square brackets in the file which is what I thought I had said. Anyway I found the use of pickle to do what I needed.

import pickle

add_val = 110
att_val = 7
val_val = 125

val = [add_val, att_val, val_val]

print(val)

with open('test', 'wb') as f:
    pickle.dump(val, f)

with open('test', 'rb') as f:
    z = pickle.load(f)

print(z)

print('add_val = ', z[0])
print('att_val = ', z[1])
print('val_val = ', z[2])
And here is the output

>>> %Run pickletest.py
[110, 7, 125]
[110, 7, 125]
add_val =  110
att_val =  7
val_val =  125
Reply
#5
Using json is preferable to use over pickle any day of the week Wink
Can keep variable information if make a dictionary,then do not need to show/recreate them in print() as you do.
>>> record =  dict(add_val=110, att_val=7, val_val=125)
>>> record
{'add_val': 110, 'att_val': 7, 'val_val': 125}
>>> record['att_val']
7
import json

record =  dict(add_val=110, att_val=7, val_val=125)
with open("my_file.json", "w") as j_out:
   json.dump(record, j_out)

with open("my_file.json") as j:
   saved_date = json.load(j)
Look at saved_date and do a print().
Output:
>>> saved_date {'add_val': 110, 'att_val': 7, 'val_val': 125} >>> saved_date['att_val'] 7 >>> for key,vaule in record.items(): ... print(f'{key} = {vaule}') ... add_val = 110 att_val = 7 val_val = 125
Reply
#6
actually, I would recommend against using pickle.
you can use csv file or json, or some other more convenient option than pickle

import csv

add_val = 110
att_val = 7
val_val = 125
 
val = [add_val, att_val, val_val]

print(val)
print(','.join(map(str, val)))
# witing to and reading from csv file - 1
with open('test.csv', 'w') as f:
    f.write(','.join(map(str, val)))

# witing to and reading from csv file - 2
with open('test.csv', 'w') as f:
    csv_wrtr = csv.writer(f)
    csv_wrtr.writerow(val)

# reading csv file - 1
with open('test.csv') as f:
    line =  f.readline().strip()
    val = [int(value) for value in line.split(',')]
 
print(val)

# reading with csv module

with open('test.csv') as f:
    csv_rdr = csv.reader(f)
    val = [int(value) for value in next(csv_rdr)]

print(val)

# reading and writing json
import json
with open('test.json', 'w') as f:
    json.dump(val, f)

with open('test.json') as f:
    val = json.load(f)

print(val)
@snippsat was faster :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Ok you've convinced me... I'll try json. Thanks all.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 1,091 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Convert dataframe from str back to datafarme Creepy 1 585 Jul-07-2023, 02:13 PM
Last Post: snippsat
  boto3 - Error - TypeError: string indices must be integers kpatil 7 1,184 Jun-09-2023, 06:56 PM
Last Post: kpatil
  Response.json list indices must be integers or slices, not str [SOLVED] AlphaInc 4 6,185 Mar-24-2023, 08:34 AM
Last Post: fullytotal
Question How to append integers from file to list? Milan 8 1,364 Mar-11-2023, 10:59 PM
Last Post: DeaD_EyE
  convert string to float in list jacklee26 6 1,817 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  "TypeError: string indices must be integers, not 'str'" while not using any indices bul1t 2 1,931 Feb-11-2023, 07:03 PM
Last Post: deanhystad
  Error "list indices must be integers or slices, not str" dee 2 1,394 Dec-30-2022, 05:38 PM
Last Post: dee
  convert a list to links Pir8Radio 3 1,043 Nov-28-2022, 01:52 PM
Last Post: Pir8Radio
  convert this List Comprehensions to loop jacklee26 8 1,418 Oct-21-2022, 04:25 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020