Extract .txt files from a zipped folder with multiple subfolders and rename these extracted files based on their file location.
Step 1: Zipped File Extraction
import os, zipfile,glob,shutil
INSERT Folder name where zipped folders are available
dir_name = r'C:\Users\user1\Documents\Extract .txt files\ZIPPED\\'
extension = '.zip'
os.chdir(dir_name) #change directory to point to this location
Check for .zip files, unzip and extract all files in "All Extracted Files" folder
for item in os.listdir(dir_name): #loop through items in this 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 zip_ref as zipfile object
zip_ref.extractall('All Extracted Files') #extract file to dir
zip_ref.close() #close file
FEED Folder name where .txt files should be saved
newpath = r'C:\Users\user1\Documents\Extract .txt files\ZIPPED\TXT Files\\'
if not os.path.exists(newpath): #if folder doesn't exist then create one
os.makedirs(newpath)
Step 2: COPY only .txt files to "TXT Files" folder*
srcdir = r'C:\Users\user1\Documents\Extract .txt files\ZIPPED\All Extracted Files\\'
dstdir = r'C:\Users\user1\Documents\Extract .txt files\ZIPPED\TXT Files\\'
for root, dirs, files in os.walk(srcdir):
for file in files:
if file[-4:].lower() == '.txt':
shutil.copy(os.path.join(root, file), os.path.join(dstdir, file))
I am stuck at how to rename these extracted files based on their location/ folder name. Ex: Rename doc1.txt to Foldername_doc1.txt.
Any ideas pls...