namelist() method not listing directories in python - python

I want to extract all the folder names from the zip file so that I can extract them separately. My login is working with one zip and but it is not working with another zip with strcuture.
root_dir = r'C:/Workspace/Neo4j/FileStore/RDAR/data.zip'
archive = ZipFile(root_dir, "r")
folder_paths = []
for file in archive.namelist():
print(file)
if file.endswith("/"):
folder_paths.append(file)
The above code is working with data10.zip but it is not listing directories in data.zip
folder strcuture of data.zip which is not working
folder structure of data10.zip
I am able extract list of folder in data10.zip as shown above, but cannot in data.zip
Any clue what might be the reason ?
Thanks
I am trying to list the directories from zip, although my code is working for one zip and is not working for another with same structure.

Related

Python, Inconsistent zip file extraction

I am trying to extract zip files using the zipfile module's extractall method.
My code snippet is
import zipfile
file_path = '/something/airway.zip'
dir_path = 'something/'
with zipfile.ZipFile(file_path, "r") as zip_ref:
zip_ref.extractall(dir_path)
I have two zip files named, test (1.1 mb) and airway (520 mb).
For test.zip the folder contains all the files but for airway.zip, it creates another folder inside my target folder named Airway, and then extracts all the files there. Even after renaming the airway.zip to any garbage name, the result was same.
Is there some workaround to get only the files extracted in my target folder? It is critical for me as I'm doing this extraction automated from django
Python version: 3.9.6;
Django version: 2.2
I ran your code and it seems to be only a problem of the zipfile itself. If you create a zipfile by selecting only the elements you get the result you got with test.zip. If you create it by selecting a folder holding the elements the folder will be there if you extract it again, no matter what you name your zip file.
I have two articles related to this:
https://www.kite.com/python/docs/zipfile.ZipFile.extractall
https://www.geeksforgeeks.org/working-zip-files-python/
Even if both of these articles do not solve your problem then I think that instead of zipping the files in the folder you just zipped the folder itself so try by zipping the files inside the folder.

Creating ZIP folder with shutil - Python

I'm trying to use shutil.make_archive but it's duplicating the folder name. Let me explain better:
My folder R360 to be ziped is located at: C:\Users\PycharmProjects\Project\media\SAE\R360\
What I am trying to do is: create a zip folder with this same name. So in the SAE directory, it should be the regular folder R360 and then R360.zip.
My code:
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}', 'zip', f"{mediaFolder}SAE/", f"{folder.split('/')[-1]}/")
The R360.zip is being created normally but the problem is that the zip folder is like this:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\R360\...
What I really wanted:
C:\Users\PycharmProjects\Project\media\SAE\R360.zip\...
It shouldn't be that R360 inside the zip folder.
I'd like to post my own question for other who are facing the same issue!
folder = C:\Users\PycharmProjects\Project\media\SAE\R360
mediaFolder = C:\Users\PycharmProjects\Project\media\
shutil.make_archive(f'{folder}/', 'zip', f"{mediaFolder}SAE/{folder.split('/')[-1]}")
This will create the zip file, without duplicating the folder itself inside the zip!

Python Unzipping files with different name to a different location

I am trying to extract the files from a zip archive and appending "EI" to each file inside it. I want these files to be extracted in a certain location. I'm new to python, hence unable to figure out.
for i in zip_list:
if ("Rally-EI" in i):
zipdata = zipfile.ZipFile(i)
zipinfos = zipdata.infolist()
for zipinfo in zipinfos:
zipinfo.filename = zipinfo.filename[:-4] + "_EI.txt"
zipdata.extract(zipinfo)
This is the code I'm using for appending the file name and it is working well. Need to extract these files to a specific location.
Thanks
Try using os.chdir() to change the current directory temporarily for this extraction. It's not the most efficient way, but, it will do the work.
Do save your current working directory using os.getcwd() to revert back to the original working directory after the extraction is done.

Copy file, rename it, iterate and repeat

I use os.renmae to rename files and move them about, but i am failing at doing the following task.
I have a main folder containing sub-folders with the structure below.
Main folder "Back", containing sub-folders named with letters and numbers e.g. A01, A02, B01, B02, etc.. inside each of those folders is a set of files, amongst them is a file called "rad" so a file path example looks something like this:
Back/A01/rad
/A02/rad
/B01/rad
.../rad
I have another sub-folder called "rads" inside the main "Back"
Back/rads
What i want to do is copy all the rad files only, from each of the folders in back and move them to the folder "rads" and name each rad file based on the folder it came from.
e.g. rad_A01, rad_A02, rad_B01, etc...
I couldnt really figure out how to increase the folder number when i move the files.
os.rename ("Back//rad, Back/rads/rad_")
I thought of making a list of all the names of the files and then do something like from x in list, do os.rename (), but i didnt know how to tell python to name the file according to the subfolder it came from as they are not a continuous series..
Any help is appreciated.
Thanks in advance
import os
for subdir, dirs, files in os.walk('./Back/'):
for file in files:
filepath = subdir+os.sep+file
if filepath.endswith("rad.txt"):
par_dir = os.path.split(os.path.dirname(filepath))[1]
os.system('cp '+filepath+' ./Back/rads/rad_'+par_dir)
save this python file beside Back directory and it should work fine!
This code iterates over each files in each subdirectory of Back, checks all files with name rad.txt, appends name of parent directory and copy to the rads folder.
Note: I saved rad files with .txt extension, change it accordingly.

Extract all audio files from a directory and put them to a new one | python

I have a folder with 1600 audio files inside which I want to extract them using the essentia extractor and changing them into a .json file in another folder in the same directory. To do this I use this line:
os.system("/usr/local/bin/essentia_streaming_extractor_music 2.mp3 2.mp3.json")
were 2.mp3 is the original file and 2 is the id of my audio file. As you can see I want to keep the name of my audio the same and just add the .json
extension. I don't know though how to keep the id of each file and what kind of iteration and recursive programming I need to do to make this happen. Can somebody help me?
import os
allfiles = os.listdir('.') # Lists all files in the current directory
for item in allfiles: # iterate over all files in the current directory
if item.endswith('.mp3'): # Checks if the file is a mp3 file
os.system('/usr/local/bin/essentia_streaming_extractor_music '+item+' '+item+'.json')

Categories