Eric
Eric

Reputation: 570

Finding Files in File Tree Based on List of Extensions

I'm working on a small python 3 utility to build a zip file based on a list of file extensions. I have a text file of extensions and I'm passing a folder into the script:

working_folder = sys.argv[1]
zip_name = sys.argv[2]

#Open the extension file
extensions = []
with open('CxExt.txt') as fp:
    lines = fp.readlines()
    for line in lines:
        extensions.append(line)

#Now get the files in the directory. If they have the right exttension add them to the list.
files = os.listdir(working_folder)
files_to_zip = []

for ext in extensions:
    results = glob.glob(working_folder + '**/' + ext, recursive=True)
    print(str(len(results)) + " results for " + working_folder + '**/*' + ext)
    #search = "*"+ext
    #results = [y for x in os.walk(working_folder) for y in glob(os.path.join(x[0], search))]
    #results = list(Path(".").rglob(search))
    for result in results:
        files_to_zip.append(result)


if len(files_to_zip) == 0:
    print("No Files Found")
    sys.exit()
for f in files:
    print("Checking: " + f)
    filename, file_extension = os.path.splitext(f)
    print(file_extension)
    if file_extension in extensions:
        print(f)
        files_to_zip.append(file)

ZipFile = zipfile.ZipFile(zip_name, "w" )

for z in files_to_zip:
    ZipFile.write(os.path.basename(z), compress_type=zipfile.ZIP_DEFLATED)

I've tried using glob, os.walk, and Path.rglob and I still can't get a list of files. There's got to be something just obvious that I'm missing. I built a test directory that has some directories, py files, and a few zip files. It returns 0 for all file types. What am I overlooking?

Upvotes: 0

Views: 90

Answers (1)

TechPerson
TechPerson

Reputation: 340

This is my first answer, so please don't expect it to be perfect.

I notice you're using file.readlines(). According to the Python docs here, file.readlines() returns a list of lines including the newline at the end. If your text file has the extensions separated by newlines, maybe try using file.read().split("\n") instead. Besides that, your code looks okay. Tell me if this fix doesn't work.

Upvotes: 1

Related Questions