how to overcome “ValueError: read of closed file” in python 3.5.1

梦想与她 提交于 2019-12-12 01:13:34

问题


I have a python script which fetches the no. of posts, followers and follows from the instagram API. The first time I ran the script, it worked perfect and gave me the required data. The script is:--

for r in range(10,12):
    var=r,sheet.cell(row=r,column=2).value
    xy=var[1]
    ij=str(xy)
    myopener=Myopen()
    url=myopener.open('https://api.instagram.com/v1/users/'+ij+'/?access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
    beta=json.loads(url)
    item=beta['data']['counts']
    data1.append(item['media'])
    data2.append(item['followed_by'])
    data3.append(item['follows'])

I have declared my FancyURLopener as follows:=

class Myopen(FancyURLopener):
version='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'

The second time I ran the script it started showing me this error:-

Traceback (most recent call last):
File "<pyshell#39>", line 7, in <module>
beta=json.load(url)
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\site-    packages\simplejson-3.8.2-py3.5-win-amd64.egg\simplejson\__init__.py", line 455, in load
return loads(fp.read(),
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
ValueError: read of closed file

How to overcome this? I have been using the same script for a week now and it never gave any error. Why today?


回答1:


Found it out myself!

The error which was received above was due to:- There were few instagram accounts which were private. So the API call is not allowed to those accounts and it will show a value error because of the JSON trying to read it and will contain HTTP error code 400.

To overcome this I changed my code like this:-

for r in range(1501,1625):
var=r,sheet.cell(row=r,column=2).value
xy=var[1]
ij=str(xy)
if xy=="Account Deleted":
    data1.append('null')
    data2.append('null')
    data3.append('null')
    continue
myopener=Myopen()
url=myopener.open('https://api.instagram.com/v1/users/'+ij+'/?access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
if url.getcode() == 400:
    data1.append('Private Account')
    data2.append('Private Account')
    data3.append('Private Account')
    continue
else:
    beta=json.load(url)
    item=beta['data']['counts']
    data1.append(item['media'])
    data2.append(item['followed_by'])
    data3.append(item['follows'])

Anybody taking help from the above can feel free to ask me any queries regarding the same!




回答2:


I had this problem in my code then there found a problem in the url address. Please check your url before opening the response.



来源:https://stackoverflow.com/questions/37024266/how-to-overcome-valueerror-read-of-closed-file-in-python-3-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!