如何动态创建包含同名文件的对象?

2024-09-27 22:20:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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')

我想写一个更简洁的代码,所以我想到了:

^{pr2}$

另一方面

'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的正确方法吗?在


Tags: 方法htmlgoogleopenutf8documentsencoding程序员
3条回答

如果你不是程序员,这很难解释,但问题是你不能有动态变量名。代码顶端的名称(例如y1992)必须显式地写在代码中。这意味着

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

在python(或我所知的任何其他编程语言)中都是不合法的。在

好消息是,现有的数据结构可以存储多个内容,以便以后访问。在本例中,您尝试存储一堆打开的文件。在python中,可以使用listdict。list是可以通过索引0、1、2等访问的有序集合,而dict是允许您通过访问项的集合。在

使用列表可能看起来像

^{pr2}$

使用dict可能看起来像

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"])

你需要的是一本字典:

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')

那应该行得通。在

您可以这样访问数据:

^{pr2}$

您看到的问题是,当表达式只能绑定到名称或容器元素时,您试图将值赋给表达式。初学者的一个常见错误是尝试动态创建变量名。这几乎总是一个坏主意(例如,如果数据创建的变量覆盖了程序正在使用的变量,该怎么办)。在

幸运的是dict,一个方便的键值存储库,来了。您可以使用简单语句创建dict

files = {}

并使用

^{pr2}$

然后,您可以引用这些文件并使用,例如

files[1990].readline()

事实上,dict值可以像其他文件一样使用。在

相关问题 更多 >

    热门问题