2014-07-02 22 views
1

我對Python非常陌生,而不是程序員。我有這樣的:如何在同一路徑中動態創建包含具有相似名稱的文件的對象?

y1990=open('Documents/python/google-python-exercises/babynames/baby1990.html', 'r', encoding='utf8') 
y1992=open('Documents/python/google-python-exercises/babynames/baby1992.html', 'r', encoding='utf8') 
y1994=open('Documents/python/google-python-exercises/babynames/baby1994.html', 'r', encoding='utf8') 
y1996=open('Documents/python/google-python-exercises/babynames/baby1996.html', 'r', encoding='utf8') 
y1998=open('Documents/python/google-python-exercises/babynames/baby1998.html', 'r', encoding='utf8') 
y2000=open('Documents/python/google-python-exercises/babynames/baby2000.html', 'r', encoding='utf8') 
y2002=open('Documents/python/google-python-exercises/babynames/baby2002.html', 'r', encoding='utf8') 
y2004=open('Documents/python/google-python-exercises/babynames/baby2004.html', 'r', encoding='utf8') 
y2006=open('Documents/python/google-python-exercises/babynames/baby2006.html', 'r', encoding='utf8') 
y2008=open('Documents/python/google-python-exercises/babynames/baby2008.html', 'r', encoding='utf8') 

我想寫一個更succint代碼,所以我想到了這一點:

path='Documents/python/google-python-exercises/babynames/baby' 
years=[year for year in range(1990,2010,2)] 
open(path+str(years[0])+'.html') # works 

在另一方面

'y'+str(years[0]) #works fine and creates string 'y1990' 

然而,當我嘗試到

'y'+str(years[0])=open(path+str(years[0])+'.html') 
    File "<stdin>", line 1 
SyntaxError: can't assign to operator 

正如你所看到的我正在嘗試創建變量名稱並動態打開文件。我已經嘗試了多種方法,並且都會產生類似的錯誤。我還發現otherposts處理我認爲是類似的問題,但我無法看到答案如何解決我的情況(很可能是我缺乏Python經驗)。人們提到列表或字典是要走的路,這是否也適用於我的問題呢?我將如何去解決這個問題?這甚至是正確的Python方式嗎?

+1

是的,只要您發現自己想要動態創建變量,該建議*總是*適用。 –

+0

謝謝大家的回答,真正澄清了我的做法。我會喜歡,但我甚至沒有聲望做到這一點。你們搖滾。 – xv70

回答

1

您看到的問題是因爲您試圖爲表達式分配值時,它們只能綁定到名稱或容器元素。一個常見的初學者錯誤是嘗試動態創建變量名稱。這幾乎總是一個壞主意(例如,如果數據創建的變量會覆蓋您的程序正在使用的變量)。

幸運的是,字典是一個便利的鑰匙價值商店。您可以創建一個字典用簡單的語句

files = {} 

,並使用

files[year] = open(path+str(years[0])+'.html') 

然後,您可以參考文件,並使用讀取它們添加到它,例如

files[1990].readline() 

事實上字典值可以像任何其他文件一樣使用。

+0

我明白了,所以我最終得到字典文件= {'1990':'text_in_file_1','1992':'text_in_file_2',...,'2008':text_in_file_10},然後通過其密鑰調用每個文件並讀取它或任何需要的,對嗎? – xv70

+0

是的,儘管代碼寫入的方式不是_filenames_,而是打開的文件本身,所以您可以調用所有常用的文件方法('read()','readline()','readlines()'等等) – holdenweb

1

你需要的是一本字典:

years = {} 
for year in range(1990, 2010,2): 
    years[year] = open('Documents/python/google-python-exercises/babynames/baby{y}.html'.format(y=year), 'r', encoding='utf8') 

這應該工作。

您可以訪問的數據是這樣的:

years[1990] or 
years[1992] 
+0

哦,那個格式技巧看起來很整潔! – xv70

1

這是很難解釋,如果你不是一個程序員,但這裏的問題是,你不能有動態的變量名。代碼最高位的名稱(例如y1992)必須在代碼中明確寫入。這意味着做類似

y199 + 2 = ... 
y199 + 4 = ... 

在python(或我知道的任何其他編程語言)中是不合法的。

好消息是存在的數據結構可以存儲多個事物以便以後輕鬆訪問。在這種情況下,您正試圖存儲一堆打開的文件。在Python中,您可以使用listdict。列表是可通過索引0,1,2等訪問的有序集合,而字典則是一個集合,可讓您通過密鑰訪問項目。

使用列表看起來像

myfiles = [] #create an empty list 
myfiles.append(open(path+str(years[0])+'.html')) 
myfiles.append(open(path+str(years[1])+'.html')) 
... 
print(myfiles[1]) 

使用字典可能看起來像

myfiles = {} #create an empty dict 
myfiles[years[0]] = open(path+str(years[0])+'.html') 
myfiles[years[1]] = open(path+str(years[1])+'.html') 
... 
print(myfiles["y1992"]) 

這兩個可以進行使用我的一環,而不是有一堆各個語句更簡潔的說我用...代表

帶循環的Dict示例:

myfiles = {} #create an empty dict 
for year in years: 
    myfiles[year] = open(path+str(year)+'.html') 
print(myfiles["y1992"]) 
+0

所以實際上創建變量的方法本身就是錯誤的吧?它需要從變量到集合對象的方法有一個小的但並非微不足道的變化。感謝您的明確答案。 – xv70

0

這裏是我想出了讀書人的輸入在此線程結束後的溶液:

path='/home/monorhesus/Documents/python/google-python-exercises/babynames/baby' 
keys=[year for year in range(1990,2010,2)] 
values=[open(path+str(year)+'.html').read() for year in years] 
files=dict(zip(keys, values)) 

對於那些誰可能有同樣的問題:第一行產生的路徑名的字符串,第二行是創建字典鍵的列表理解,第三行是創建字典值的列表理解(注意.read,所以它是實際的文件轉儲),最後一個是從兩個列表創建字典。

相關問題