#Python help with files not extracting.

8 messages · Page 1 of 1 (latest)

woeful flume
#

Also print(file) not showing any files which I expect it is why I'm not getting any file extraction but I was expecting to get a print(file)
Why not ?

fresh mist
#

We have no idea. You need to share the code so we can see what it’s actually doing

woeful flume
woeful flume
#

So I actually know why this occurs now.
Here is the sample code.

#doesn't work to remove top level folder
import zipfile
import os

os.chdir(os.path.expanduser("~"))
def extract_files(zip_path, files_to_extract, extract_to='.'):
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        for file in zip_ref.namelist():
            if file in files_to_extract:
                print(file)
                zip_ref.extract(file, extract_to)

# Example usage
zip_path = "FreedomCoin-Core-Linux"
zip_file = "FreedomCoin-Core-Linux.zip"
files_to_extract = [f"{zip_path}/freedomcoin-cli", f"{zip_path}/freedomcoind"]
extract_files(zip_file, files_to_extract, "FreedomCoin/Freed1") 

I figured out that I need to include the top level folder specifically in the .zip file.
This in turn also extracts the top level folder too which is what I was trying to avoid.

#

If I simply try "freedomcoin-cli" without calling the complete path inside the .zip file then the file does not extract.
When I do call the folder it extracts but with the folder too.

woeful flume
#

I guess I can close this post since I figured out why but now trying to write it so I can exclude the folder.

mystic gyro
#

Good to hear! Can you let us know what the reason was?

woeful flume
#

OH, sorry yes
The reason was because when you extract a .zip file. such as extractall() it also extracts the folder structure such as: Folder/somefile.txt.

So you cannot just call the file.txt it must be Folder/file.txt

For example AI suggests this:

import zipfile

with zipfile.ZipFile('archive.zip', 'r') as zip_ref:
    zip_ref.extract('file_to_extract.txt', 'destination_folder/') 

Yes this works but you will end up with "Folder/file_to_extract.txt" inside of destination_folder. aka "destination_folder/Folder/file_to_extract.txt"

It's not wrong but it sort of insinuates that you can extract only the file and nothing else which is wrong it will include the folder that it's inside of.

Which is why I could not extract it because I wasn't even calling out the correct source file which was located in "FreedomCoin-Core-Linux/freedomcoin-cli" etc etc.

Now if I can strip the Folder top level without creating it and copying it. Just would like to extract only file.
I think I may just have to copy to another destination and delete the old folder instead. Maybe easier for me to write at least.