2014-08-28 52 views
0

我想發佈一個圖像到twitter每小時出一個文件夾。Tweepy更新與媒體錯誤

import os, tweepy, time, sys, 
path="C:\Users\Kenny\Desktop\dunny" 
files=os.listdir(path) 

CONSUMER_KEY = 'hide' 
CONSUMER_SECRET = 'hide' 
ACCESS_KEY = 'hide' 
ACCESS_SECRET = 'hide' 
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) 
api = tweepy.API(auth) 

for i in path: 
    api.update_with_media(files) 
    time.sleep(3600) 

這是我得到的錯誤消息,如果我嘗試運行代碼。

C:\Users\Kenny\Desktop>python htmlparse.py 
Traceback (most recent call last): 
    File "htmlparse.py", line 14, in <module> 
    api.update_with_media(files) 
    File "C:\Python27\lib\site-packages\tweepy\api.py", line 98, in update_with_me 
dia 
    headers, post_data = API._pack_image(filename, 3072, form_field='media[]', f 
=f) 
    File "C:\Python27\lib\site-packages\tweepy\api.py", line 713, in _pack_image 
    if os.path.getsize(filename) > (max_size * 1024): 
    File "C:\Python27\lib\genericpath.py", line 49, in getsize 
    return os.stat(filename).st_size 
TypeError: coercing to Unicode: need string or buffer, list found 

回答

2

你需要讓你的path串原始字符串字面量:

path = r"C:\Users\Kenny\Desktop\dunny" 

或使用雙反斜線:

path = "C:\\Users\\Kenny\\Desktop\\dunny" 

或使用正斜槓:

path = "C:/Users/Kenny/Desktop/dunny" 

\U(來自"C:\Users...")是一個用於定義32位十六進制值的escape sequence。這就是你得到Unicode錯誤的原因。


另一個問題是您的for循環在底部。試試這個(你需要import os在頂部):

for i in files: 
    filename = os.path.join(path, i) 
    api.update_with_media(filename) 
    time.sleep(3600) 

以前,當您使用for i in path:,你的字符串path在遍歷每個字符。然後,在循環體中,api.update_with_media(files)試圖發送文件名的完整列表,當該函數只接受一個。

+0

仍然不工作TypeError:強制爲Unicode:需要字符串或緩衝區,找到列表 – Kenny 2014-08-28 16:39:03

+0

@ user3834405請參閱我的更新 - 「for」循環中的邏輯錯誤。 – MattDMo 2014-08-28 16:58:02

+0

現在我得到tweepy.error.TweepError:無法訪問文件 – Kenny 2014-08-28 17:07:34