I am new with Python and confused regarding the scope of variables which are declared inside loops. I have seen some examples but it is hard for me to understand it in my specific case.
For example, I saw the following code segment 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)
I basically have the above code repeated in very much the same way but with different statements executed inside the loops. These similar code segments are one after the other inside my __main__
. My question is: in that repeated code do I need to give new names to the variables for archive
, id
, file
, files
, outfile
or not? Will there be a clash or something? Are there any good-practice concerns to keep in mind?