0

I want to read a tuple from a file and convert it to a list.

The file has this: (1,2,3)

My code:

with open('scores.txt','r+') as scores:
    score_file=list(scores.read())
    print(score_file)

The output is: ['(', '1', ',', '2', ',', '3', ')'] but I want that: [1,2,3] How can I do this:

3 Answers3

2

As the scores.read() returns the object of type str, with list(scores.read()), the str object is broken into the list with individual characters.

You could use ast.literal_eval() to convert to the right datatype and then convert to list as:

import ast
with open('scores.txt','r+') as scores:
    score_file = scores.read()
    score_file = list(ast.literal_eval(score_file))
    
    print(score_file)
    print(type(score_file))

Output:

[1, 2, 3]
<class 'list'>
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
0

You could do

lst = []

with open('scores.txt','r+') as scores:
    score_file = scores.read()
    for item in score_file:
        if item != '(' and item != ')' and item != ',':
            lst.append(int(item))

print(lst)

which iterates through the scores and adds them as integers to a list.

Daniel
  • 275
  • 1
  • 9
  • I have this error message: `Traceback (most recent call last): File "c:\Users\Local-Admin\Documents\_git\test.py", line 6, in lst.append(int(score)) ValueError: invalid literal for int() with base 10: '('` –  Mar 01 '21 at 09:25
  • @NicholasKrebs Sorry, just edited my answer to account for the non-integer items in the list. – Daniel Mar 01 '21 at 09:28
  • thanks but now the problem is if the number is like 11, it writes `(1,1)` when the script runs twice –  Mar 01 '21 at 10:17
  • @NicholasKrebs Sorry, without the data you are using it's hard to test my code. In that case you are better off using one of the other answers as they are better than my method anyway. – Daniel Mar 01 '21 at 10:26
  • yes i know i only wanted you to know with a number with more than one digit its not possible. and i only use numbers –  Mar 01 '21 at 10:38
0

If you prefer not to import modules you could use list comprehension. For each score in scores you strip the parentheses and split on the comma. Then cast to int.

with open('scores.txt','r+') as scores:
    for score in scores:
        print([int(i) for i in score.strip('()').split(',')])

>>> [1, 2, 3]
ScootCork
  • 3,411
  • 12
  • 22