2015-11-11 74 views
-1

所以我有下面的代碼,我試圖導出一個CSV並立即在Python中打開它。文件命名時使用路徑

# define weekly pull code 
def GT_Weekly_Run(keys): 
    # connect to Google 
    connector = pyGTrends(google_username, google_password) 
    # make request 
    connector.request_report(keys, geo="US") 
    # wait a random amount of time between requests to avoid bot detection 
    time.sleep(randint(5, 10)) 
    # download file 
    connector.save_csv(path, '_' + "GT_Weekly" + '_' + keys) 

    name = path, '_' + "GT_Weekly" + '_' + keys 
    with open(name + '.csv', 'rt') as csvfile:  
     csvReader = csv.reader(csvfile) 
     data = [] 

     data = [row for row in csvReader if row and row[0].startswith("20")] 
     week_df = pd.DataFrame(data) 

     cols = ["Date", "Trend"]  
     week_df.columns = [cols] 

問題是我無法將保存文件名與打開的文件名匹配。已嘗試了一些東西,但不斷收到有關的錯誤

IOError: [Errno 2] No such file or directory: 'GT_Weekly_football.csv' 

TypeError: can only concatenate tuple (not "str") to tuple 

有什麼看起來不對。我只需要將文件保存爲X並使用相同的名稱(X)將其重新導入。

謝謝!

+1

'keys'是一個元組嗎? – McGlothlin

+0

'name = path,'_'+「GT_Weekly」+'_'+ keys'使'name'成爲一個雙元組元組。但在'open'調用中,您嘗試使用'name +'.csv''將字符串連接到該元組。你可能打算做'name = path +'_'+「GT_Weekly」+'_'+ keys'。但是,正如Martin指出的那樣,在構建文件路徑時最好使用'os.path.join'函數。 –

+0

Key's只是一個單一的字符串,「棒球」 – ATMA

回答

0

我建議你創建一個變量來保存文件名。這樣,相同的名稱將用於創建和加載回來。

import os 

# define weekly pull code 
def GT_Weekly_Run(keys): 
    # connect to Google 
    connector = pyGTrends(google_username, google_password) 
    # make request 
    connector.request_report(keys, geo="US") 
    # wait a random amount of time between requests to avoid bot detection 
    time.sleep(randint(5, 10)) 

    # download file 

    filename = "_GT_Weekly_" + keys 
    connector.save_csv(path, filename) 

    with open(os.path.join(path, filename), 'rt') as csvfile:  
     csvReader = csv.reader(csvfile) 
     data = [] 

     data = [row for row in csvReader if row and row[0].startswith("20")] 
     week_df = pd.DataFrame(data) 

     cols = ["Date", "Trend"]  
     week_df.columns = [cols] 

這是比較安全的使用Python的os.path.join功能來創建完整的文件名。

也看看你傳遞給GT_Weekly_Runkeys參數,它應該只是一個簡單的字符串。

+0

感謝您的幫助。沒有得到以下錯誤:TypeError:save_csv()需要3個參數(給出2個) – ATMA

+0

現在試試看,'save_csv'函數顯然需要單獨的路徑。 –

+0

是的,這是更廣泛的類中的一種方法。回溯(最近通話最後一個): 文件 「」,2號線,在 GT_Weekly_Run( 「足球」) 文件 「」,作爲csvfile與開行14,在GT_Weekly_Run (os.path.join(路徑,文件名), 'RT'): IO錯誤:[錯誤2]沒有這樣的文件或目錄: 'Forecast_Process \\ _ GT_Weekly_football' – ATMA