简体   繁体   中英

Python: List pulled from txt file as string not recognised as list

I saved the show data from the epguide API in a txt file, which looks like this:

[{'epguide_name': 'gooddoctor', 'title': 'The Good Doctor', 'imdb_id': 'tt6470478', 'episodes': ' http://epguides.frecar.no/show/gooddoctor/ ', 'first_episode': ' http://epguides.frecar.no/show/gooddoctor/first/ ', 'next_episode': ' http://epguides.frecar.no/show/gooddoctor/next/ ', 'last_episode': ' http://epguides.frecar.no/show/gooddoctor/last/ ', 'epguides_url': ' http://www.epguides.com/gooddoctor '}]

When I now try to read it as a list in python it doesn't recognise it as such but only as a string despite the square brackets:

    with open(file_shows, 'r', encoding='utf-8') as fs:
       fs = fs.read()
       print(type(fs))
       print(next((item for item in list if item['title'] == show), None)['episodes'])

Type remains a str and thus the search is also not working. How can I convert the data "back" to a list?

One solution is as follows,

with open('fileShows.txt', 'r', encoding='utf-8') as fs:
    fs = fs.read()
    print(type(fs))
    my_list = list(fs)
    print(type(my_list))

Another is,

with open('fileShows.txt', 'r', encoding='utf-8') as fs:
    fs = fs.read()
    print(type(fs))
    my_list = eval(fs)
    print(type(my_list))

Basically eval() converts yours str retrieved from the file pointer to its base type which is of type list.

Try the following:

import json
with open(file_shows, 'r', encoding='utf-8') as fs:
       data = json.loads(fs.read().replace("'",'"')) # data will be list and not str

Enjoy!

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