简体   繁体   中英

Python import list from text file as list

[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?

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)

.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.

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)

您可以这样做:mylist = mylist [1:-1] .split(“,”)[1:-1]删除了括号

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM