I'm trying to find python script to extract 3 zip files in a folder then deleting the zip files and modifying the extracted files name. actually I need to take only first 80 characters from the name of each extracted file.
If anyone can help. thanks
I used below script
import zipfile,os,fnmatch, glob
path = "Directory\\"
dir_list = os.listdir(path)
counter = 1
for file in dir_list:
with zipfile.PyZipFile(path+"\\"+file,'r') as zObject:
zObject.extractall(path=path)
zObject.close()
counter +=1
os.unlink(path +file)
os.chdir("Directory\\")
for file in os.listdir():
print(file)
I can see unzipping and zipfiles deletion done, but when I tried to rename the files I can see below error so I can't move to next step
File "C:\Users\melnagga\AppData\Local\Programs\Python\Python311\Lib\zipfile.py", line 1366, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file
The Key for me was to extract the zip files into other directory, then rename extracted files in the new directory
used code is as shown below:
import zipfile,os
path = "Directory_pth\\"
dir_list = os.listdir(path)
for file in dir_list:
with zipfile.PyZipFile(path+"\\"+file,'r') as zObject:
zObject.extractall(New Directory_path")
os.unlink(path +file)
zObject.close()
os.chdir("New Directory_path")
for file in os.listdir():
name, ext = os.path.splitext(file)
splitted = name.split("-")
new_name = f"{splitted[0]}_new{ext}"
os.rename(file,new_name)
Thanks to everyone tried to help
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.