Attribute Error for Rename / Replace - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Attribute Error for Rename / Replace (/thread-23576.html) |
Attribute Error for Rename / Replace - warden89 - Jan-06-2020 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! 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
RE: Attribute Error for Rename / Replace - ichabod801 - Jan-06-2020 Well, file_list is a list, while replace is a method of strings. You can't use a string method directly on a list of strings, you have to loop through the list and apply it to each of the strings individually. You might always want to look at the maketrans method of strings. RE: Attribute Error for Rename / Replace - snippsat - Jan-06-2020 (Jan-06-2020, 05:18 PM)warden89 Wrote: . My directory has files that look like this: 20191210.092030_Monthly_Service_Cost_12-10-2019-02-17A would write regex to clean it up first,then add .zip .Example. >>> import re >>> >>> s = '20191210.092030_Monthly_Service_Cost_12-10-2019-02-17' >>> r = re.search(r'_(.*[a-zA-Z])', s) >>> result = r.group(1).replace('_', '') >>> print(f'{result}.zip') MonthlyServiceCost.zip >>> >>> s = '9999.777.44_Monthly_Service_Cost_111-777_999.44' >>> r = re.search(r'_(.*[a-zA-Z])', s) >>> result = r.group(1).replace('_', '') >>> print(f'{result}.zip') MonthlyServiceCost.zip RE: Attribute Error for Rename / Replace - warden89 - Jan-06-2020 Hi - thanks for the recommendation - it worked! Some of the zipped files in question have periods "." in the file name - is it possible to remove them without messing up the file association? I imagine I would need to add an if/else statement of some kind? import os, zipfile, string #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) def rename_files(): #Obtain the file names from the folder for file_name in file_list: #Rename the files inside of the folder. os.rename(file_name, file_name.translate(str.maketrans('','','0123456789_-'))) rename_files()
RE: Attribute Error for Rename / Replace - perfringo - Jan-07-2020 Just playing with string .split method . It assumes that needed part is between first and last underscore (as provided in example). >>> s = '20191210.092030_Monthly_Service_Cost_12-10-2019-02-17' >>> f"{''.join(s.split('_', maxsplit=1)[1].rsplit('_', maxsplit=1)[0].split('_'))}.zip" 'MonthlyServiceCost.zip' RE: Attribute Error for Rename / Replace - warden89 - Jan-07-2020 (Jan-07-2020, 08:22 AM)perfringo Wrote: Just playing with string .split method . It assumes that needed part is between first and last underscore (as provided in example). I'm not sure how to incorporate this into the code I already have - apologies I am very new to this. If I can get it working though, it looks like it might be a better solution then what I commented out above it. import os, zipfile, string, re from shutil import copyfile ###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) def rename_files(): #Obtain the file names from the folder for file_name in file_list: #Rename the files inside of the folder. #os.rename(file_name, file_name.translate(str.maketrans('','','0123456789_-'))) #Removes characters noted to the left f"{''.join(file_list.split('_', maxsplit=1)[1].rsplit('_', maxsplit=1)[0].split('_'))}.zip" rename_files()
Renaming files within Parent folders AFTER their parent folder - warden89 - Jan-07-2020 Hi All - I am writing a script that manipulate multiple a .ZIP file - right now my script renames the zip file, unzips the file directory and then deletes the zip file. What I am really struggling with is renaming the file within the now unzipped directory. I have multiple, newly unzipped folders all with files called "report.csv" within... These files need to be renamed based on their parent folder name. I have no idea how to do that. Ex: 20191210.092030__ITFM_12-10-2019-02_17.zip --> ITFM.zip ... C:\Users\m88576\Desktop\UnzipDirectory\ITFM\report.csv --> C:\Users\m88576\Desktop\UnzipDirectory\ITFM.csv 20191210.092030_Monthly_Service_Cost_12-10-2019-02-17.zip --> MonthlyServiceCost.zip ... C:\Users\m88576\Desktop\UnzipDirectory\MonthlyServiceCost\report.csv --> C:\Users\m88576\Desktop\UnzipDirectory\MonthlyServiceCost.csv TL;DR: I need the file (report.csv) in question to be named after its parent folder and be moved one folder up Any advice or guidance would be extremely appreciated. Thanks! My code: import os, zipfile, string, re from shutil import copyfile ###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 print('1...Setting Parameters...') ###Rename Zip Files### file_list = os.listdir(dir_name) def rename_files(): #Obtain the file names from the folder for file_name in file_list: #Rename the files inside of the folder. os.rename(file_name, file_name.translate(str.maketrans('','','0123456789_-'))) #Removes characters noted to the left rename_files() print("2...Zip Files Renamed...") ##Unzip & Rename File Directories### filename = ['report.csv'] for item in os.listdir(dir_name): # loop through items in dir if item.endswith(".zip"): # check for ".zip" extension file_path = os.path.join(dir_name, item) # get zip file path with zipfile.ZipFile(file_path) as zf: # open the zip file for target_file in filename: # loop through the list of files to extract if target_file in zf.namelist(): # check if the file exists in the archive target_name = os.path.splitext(file_path)[0] # generate the desired output name: target_path = dir_name # output path zf.extractall(target_name) # extract file to dir print("3...Files Unzipped...") ###Delete Zip Files### for item in os.listdir(dir_name): if item.endswith(".zip"): os.remove(item) print("4...Zip files deleted...") |