Search code examples
pythonrenameunzip

Rename file after unzipping


I'm trying to rename files before extraction using os.rename()

def unzip(date,day,zip_file):

        dest_dir = 'C:/Users/mbelahce040119/PycharmProjects/kpi/flats'

        with ZipFile(zip_file) as zipObj:
            files_sat = list()
            for zip_info in zipObj.infolist():
                if zip_info.filename[-1] == '/':
                    continue
                if zip_info.filename.startswith(date,42,50):
                    files_sat.append(zip_info.filename)
                    zip_info.filename = os.path.basename(max(files_sat))
            print(max(files_sat))
            zipObj.extract(max(files_sat), dest_dir)
            old_file = os.path.join(dest_dir,max(files_sat))
            new_file = os.path.join(dest_dir,date+'_D+'+day+'.csv')
            os.rename(old_file,new_file)

However, I don't know how to pass the new file name to the extract function and don't know if it should be before or after extraction. For now no extraction is happening because I changed the name in the line before.


Solution

  • I figured it out. The problem was the fact that I had already changed the filename to basename so I had to rename using the basename.

    def unzip(date,day,zip_file):
    
            dest_dir = 'C:/Users/mbelahce040119/PycharmProjects/kpi/flats'
    
            with ZipFile(zip_file) as zipObj:
                files_sat = list()
                for zip_info in zipObj.infolist():
                    if zip_info.filename[-1] == '/':
                        continue
                    if zip_info.filename.startswith(date,42,50):
                        files_sat.append(zip_info.filename)
                        zip_info.filename = os.path.basename(max(files_sat))
                print(max(files_sat))
                final_file = max(files_sat)
                zipObj.extract(final_file, dest_dir)
                old_file = os.path.join(dest_dir,os.path.basename(final_file))
                new_file = os.path.join(dest_dir,date+'_D+'+day+'.csv')
                os.rename(old_file,new_file)