简体   繁体   English

解压缩并重命名

[英]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. 这些链接以.zip归档文件的形式下载,每个归档文件都包含一个.tif图像,该图像需要提取并命名为与父zip文件夹相同的名称。 Everything about the script works correctly except for the extracting and renaming the zip folder portion below 除了解压缩和重命名下面的zip文件夹部分外,有关脚本的所有内容均正常运行

The script still executes, but when you view the output, the .tif is in the correct directory, but has not been renamed. 该脚本仍将执行,但是当您查看输出时,.tif位于正确的目录中,但尚未重命名。

What is the correct way to get the script to rename the extracted .tif? 什么是使脚本重命名提取的.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: 您需要像这样的os.walkglob.glob

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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