简体   繁体   中英

Unzip and Rename

I have written/ pieced together the following code to to compile a list of links and download the link. The links are downloaded as .zip archives each containing one .tif image that needs to be extracted and named the same as is parent zip folder. Everything about the script works correctly except for the extracting and renaming the zip folder portion below

The script still executes, but when you view the output, the .tif is in the correct directory, but has not been renamed.

What is the correct way to get the script to rename the extracted .tif?

also any other suggestions for improvement would be welcomed

FULL SCRIPT

import pandas as pd
import urllib
import os
import zipfile

data = pd.read_csv('StateRaster.csv')
links = data.SCAN_URL
file_names = data.API_NUMBER +"_"+ data.TOOL
dir = data.FOLDER +"/"+ data.SECTION2
root='g:/Data/Wells'
n=0
e=0

for link, file_name,dir in zip(links, file_names,dir):
    try:
        u = urllib.request.urlopen(link)
        udata = u.read()
        os.makedirs(os.path.join(root,dir), exist_ok=True)
        f = open(os.path.join(root,dir,file_name+".zip"), "wb+")
        f.write(udata)
        f.close()
        u.close()
        zip_ref = zipfile.ZipFile((os.path.join(root,dir,file_name+".zip")), 'r')
        #for filename in (os.path.join(root,dir,file_name+".zip")):
        zip_ref.extractall((os.path.join(root, dir)))
        for filename in ((os.path.join(root,dir))):
            if filename.endswith(".tif"):
                os.makedirs(os.path.join(root,dir,file_name+".tif"), exist_ok=True)
                os.rename(filename,file_name+".tif")

        zip_ref.close()

        n += 1
        print ('Pass',n,'Fail',e,'Total',n+e)
    except:
        e+=1
        print ('Error-Pass',n,'Fail',e,'Total',n+e)
        print("Done!!!!!")

The problem is around

    for filename in ((os.path.join(root,dir))):

There is no need to put (( and )) around and this line simply iterates over characters. You need to os.walk or maybe glob.glob like this:

    for filename in glob.glob(os.path.join(root, dir, "*.tif")):
         print(filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM