Jan-06-2020, 04:38 PM
Hello Everyone -
I'm very new to python and I have a use case where I need to rename .zip files and then extract. I think I have the extraction part down (it is commented out for the time being) but I am having trouble with the rename portion. My directory has files that look like this: 20191210.092030_Monthly_Service_Cost_12-10-2019-02-17
Ultimately, I would like my zip file to look like MonthlyServiceCost.zip ... Feedback would be greatly appreciated!
I'm very new to python and I have a use case where I need to rename .zip files and then extract. I think I have the extraction part down (it is commented out for the time being) but I am having trouble with the rename portion. My directory has files that look like this: 20191210.092030_Monthly_Service_Cost_12-10-2019-02-17
Ultimately, I would like my zip file to look like MonthlyServiceCost.zip ... Feedback would be greatly appreciated!
import os, zipfile #Parameters dir_name = 'C:\\Users\\m88576\\Desktop\\UnzipDirectory' # Defines target directory extension = ".zip" #Defines target extension (zip) os.chdir(dir_name) # change working dir to target directory #Rename Zip Files file_list = os.listdir(dir_name) #creates variable print(file_list) #List all files in the directory before extract file_list_rename = file_list.replace('.','').replace('1', '').replace('2', '').replace('3', '').replace('4', '').replace('5', '').replace('6', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('_', '').replace('-','') os.rename(file_list, file_list_rename) #os.rename(file_list, file_list.strip('123456789_'))#removes numerical and non-string characters #Unzip Files #for item in os.listdir(dir_name): # loop through items in dir # if item.endswith(extension): # check for ".zip" extension # file_name = os.path.abspath(item) # get full path of files # zip_ref = zipfile.ZipFile(file_name) # create zipfile object # zip_ref.extractall(dir_name) # extract file to dir # zip_ref.close() # close file # os.remove(file_name) # delete zipped file print(file_list) #List all files in the directory after extract
Error:Traceback (most recent call last):
File "C:\Users\m88576\Desktop\UnzipDirectory\TargetUnzip.py", line 14, in <module>
file_list_rename = file_list.replace('.','').replace('1', '').replace('2', '').replace('3', '').replace('4', '').replace('5', '').replace('6', '').replace('7', '').replace('8', '').replace('9', '').replace('0', '').replace('_', '').replace('-','')
AttributeError: 'list' object has no attribute 'replace'