0

Let's say that that I have the following files in a folder:

File1.txt
File2.py
File3.txt

I want to create a ZIP archive, but only of the .txt files. I could use a for loop to iterate through the files of this folder, like so:

for folder, subfolder, files in os.walk(path):

At this point, I'm not sure how I can efficiently filter out anything that isn't a .txt file. For this example, my first thought is to walk through the directory where my files are stored, and do something like this:

for folder, subfolder, files in os.walk(path):
    for i in files:
        if i == 'File1.txt' OR i == 'File3.txt':
            myZip.write(i)

I think this would work since these are the only files in the folder, but it wont work if there are more files in the folder. What's a better way to only write certain types of files to a ZIP archive?

2 Answers2

0

You can check if the file name ends with .txt:

for folder, subfolder, files in os.walk(path):
    for i in files:
        if i.endswith('.txt'):
            myZip.write(i)
Matteo Zanoni
  • 3,429
  • 9
  • 27
  • This is exactly what I was looking for. Definitely gonna remember this for the future. Thanks for the assist! –  Mar 03 '22 at 21:53
0

This is much simpler using pathlib, which provides recursive globbing.

from pathlib import Path


for f in Path(path).glob('**/*.txt'):
    myZip.write(f)
chepner
  • 497,756
  • 71
  • 530
  • 681