0
[2, 'hello', 3, 'good'] - is stored in myfile.txt on one line


 with open(myfile,'r') as f:
        myList = f.readlines()

but when I try to retrieve the first index, so "2' by using myList[0], the first square brackets is retrieved.

How can I set the imported line into a list?

1
  • 2
    Because it comes as string when you read from file. You can do myList = eval(myList) Commented Feb 25, 2018 at 12:47

4 Answers 4

2

.readlines() method reads lines of text from file, separated with the new line character and returns a list, containing those lines, so that's not the case.

You could have read the contents of the file and eval it like this:

with open(myfile,'r') as f:
    my_list = eval(f.read())

Note, that the usage of eval is considered to be a really bad practice, as it allows to execute any python code written in the file.

Sign up to request clarification or add additional context in comments.

Comments

2

use the ast module to convert the string to a list object

Ex:

import ast
with open(myfile,'r') as f:
        data= f.read()
        myList = ast.literal_eval(data)

Comments

0

You can use the json module for this (since a list is a valid json object):

import json
with open(myfile) as f:
    myList = json.load(f)

Comments

0

You could do: mylist = mylist[1:-1].split(",") [1:-1] gets rid of brackets

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.