2016-08-13 21 views
0

在我學習數組時,我一直在使用path = open(Testfilename)作爲開始的幾個python腳本。現在我正在處理字典,我想查看是否可以使用此功能打開多個文件。使用path = open()功能打開多個文件

fav_cars = {} 

for c in cars: #I have a few separate CSV files with different cars 
    path = open() 

我基本上希望各地不同的汽車,用戶將在迴路中。正如上面提到的,我知道如何打開一個文件,但我努力學習,以打開多個文件。我試着這樣做:

path = open('F-150.csv', 'Silverado.csv', 'Mustang.csv', 'Tesla.csv', 'r'), 

,但沒有工作,我得到了一個錯誤代碼TypeError: an integer is required

UPDATE:

文件是用所謂的「顏色」的標題做一個列的車。有6行的六種顏色:紅,藍,黃,黑,白,綠

cars = ['F-150','Silverado','Mustang','Tesla','Juke','Corolla'] 

fav_cars = {} 
for c in cars: 
    path = open() # wanting to open multiple files here 
    car_colors = {} #colors for each car in cars 
    for temp_dict in path: 
     if not temp_dict.startswith("#"): #to get rid of the header "colors in the file 
      if values in user_input: #value is the car color 
        car_colors.update({values}) 
        fav_cars.update({c:car_colors}) 

我只使用了汽車用戶的輸入,user_inputs,當我的raw_input使用要求它。希望這有助於。

+0

打開文件後,您想如何處理這些文件? – poke

+0

你能提供一些汽車CSV文件的例子,預期的用戶輸入和預期的輸出嗎? – Cychih

回答

0

你應該做的是這樣的:

fav_cars = {} 

for c in cars: 
    with open(c, 'r') as f: 
     fav_vars[c] = f.readlines() 

內置open函數期望只有一個文件作爲參數,第二個是你打開文件的模式。

+0

我這樣做了,但得到錯誤AttributeError:'文件'對象沒有'startswith'屬性。我使用:如果不是temp_dict.startswith(「#」),所以我可以刪除標題。 –

+0

我想你會在閱讀文件之前嘗試對文件的內容進行操作。我修改了我的答案,將文件的內容添加到文件對象的列表中。 –

+0

嗯。 fav_cars仍然只給我{}的輸出。 –