2

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?

dizcotec
  • 23
  • 3

2 Answers2

0

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.

Arpit Maiya
  • 177
  • 7
0

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!

Gabio
  • 9,126
  • 3
  • 12
  • 32
  • Hi Gabip, thanks for responding. I tried json.loads(). It gives me the following error: 'TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper' It's weird because type fs is . – dizcotec Apr 02 '20 at 05:57
  • Updated my solution, please try now :) – Gabio Apr 02 '20 at 06:11
  • Hi Gabip, you're amazing. Thanks for still trying!! I wrote a quick file again to test your new solution since I'm keen of knowing if it works. Unfortunately now I'm getting this error: 'json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)'. Arpit's eval() solution worked though. – dizcotec Apr 02 '20 at 11:09
  • @dizcotec unfortunately me solution won't work here. I didn't notice that your json elements are quoted with single quotes instead of double quotes and this cause your json to be invalid so `json` module is not able to parse it. If you replace all the single quotes with double with `fs.read().replace("'",'"')` it will work but in your case, I guess using `eval` is better. Anyway, I've update again my solution if you want to try it (I checked it on my machine and it works well). – Gabio Apr 02 '20 at 11:18