我對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方式嗎?
是的,只要您發現自己想要動態創建變量,該建議*總是*適用。 –
謝謝大家的回答,真正澄清了我的做法。我會喜歡,但我甚至沒有聲望做到這一點。你們搖滾。 – xv70