【发布时间】:2016-04-09 19:21:41
【问题描述】:
我是 Python 新手,对在循环内声明的变量的范围感到困惑。我看过一些例子,但在我的具体情况下很难理解。
比如我看到了如下代码段here:
with ZipFile(self.archive_name, "r") as archive:
for id, files in data.items():
if files:
print("Creating", id)
dirpath = os.path.join(directory, id)
os.mkdir(dirpath)
for file in files:
match = pattern.match(filename)
new = match.group(2)
new_filename = os.path.join(dirpath, new)
content = archive.open(file).read()
with open(new_filename, "wb") as outfile:
outfile.write(content)
我基本上以非常相同的方式重复了上面的代码,但在循环中执行了不同的语句。 这些相似的代码段在我的__main__ 中一个接一个。我的问题是:在那个重复代码中,我是否需要为变量赋予新名称 对于archive、id、file、files、outfile 是否?会不会有冲突什么的?是否有任何良好实践问题需要牢记?
【问题讨论】:
-
修改了我的问题以添加有关这些相似代码段所在位置的信息。
标签: python