0

So I have a list that contains paths to two text files:

file_paths = ['/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_H_20230703.TXT', '/tmp/bmex-2023-07-28-w0hrsh25/MFII_MC_TICK_AE_20230703.TXT']

I want to write these two text files into a zip file, I do:

with ZipFile(str(new_file), 'w', compression=ZIP_DEFLATED) as merged_archive:
    for file in file_paths:
        with open(file, 'r') as f:
            merged_archive.writestr(file, f.read())

I've omitted some details about new_file, it's quite complex but I can include it if it is relavant. I don't think it is, the only relavant part is that merged_archive is the zip file in question.

When I open the zip file I expect the two text files, but when I do the above and open the zip file after, I get:

zip_file/
├── tmp/
    ├── embedded/
        ├── bmex-equities3-2023-07-28-n3matya5
             └── two_text_files_are_here

I can understand why it is creating these directories, clearly becuase I am feeding it file paths instead of the file names.

But I can't figure out a solution, becuase if I feed it the file names only, it will return something like:

FileNotFoundError: [Errno 2] No such file or directory: 'MFII_MC_TICK_H_20230703.TXT'

Which I totally understand!

Any ideas?

ifrj
  • 91
  • 7
  • **Edit2:** failed to properly read, [see this Q&A](https://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format). -- You put the whole path into `writestr`, which creates it inside the ZIP. Extract just the filename and use that. **Edit:** [shutil.make_archive](https://docs.python.domainunion.de/3/library/shutil.html#shutil.make_archive) may also interest you when zipping all files in a folder. – ivvija Jul 28 '23 at 10:49
  • Thanks @ivvija, as mentioned towards the bottom of the question, if I just put the filename, I run into a `FileNotFoundError` - any ideas how to overcome this? – ifrj Jul 28 '23 at 11:04
  • OK ignore my comment - I just clicked into your link! – ifrj Jul 28 '23 at 11:05

0 Answers0