# Write the filewith open((file_location+file_name), "wb") as output_file:
output_file.write(response.content)
# Unzip itwith tarfile.open((file_location+file_name), "r:gz") as tarObj:
tarObj.extractall(path=file_location)
# Remove compressed file
os.remove(file_location+file_name)
接下来,我编写了一个函数:
target_dir = keyvalue[1] # target directory is stored in this tuple
subdirs = get_imm_subdirs(target_dir) # function to get subdirectoriesfor f in subdirs:
c = os.listdir(os.path.join(target_dir, f)) # find file in subdir
shutil.move(c, str(target_dir)+"ALL_FILES/") # move them into 1 subdir
os.rmdir([os.path.join(target_dir, x) for x in subdirs]) # remove other subdirs
with tarfile.open('musthaves.tar.gz') as tarObj:
for member in tarObj.getmembers():
if member.isfile():
member.name = os.path.basename(member.name)
tarObj.extract(member, ".")