我是Python新手,對於在循環中聲明的變量範圍感到困惑。我看過一些例子,但在我的具體情況下,我很難理解它。循環中的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
與否?會有衝突或什麼?要記住有什麼好的做法?
修改我的問題,添加關於這些類似的代碼段位於何處的信息。 –