0

I want to add the file extensions found in the function to the line of code where I specified "HERE". In other words, not only ".txt", but also the extensions of the above function should be brought that part. In short, I want to associate the following code with the function.

Can you help me, with this?

def extention_finder(file_path):
    
    if ".XLSX" in file_path.upper():
        ext = ".xlsx"
    elif ".XLS" in file_path.upper():
        ext = ".xls"
    elif ".TXT" in file_path.upper():
        ext = ".txt"
    elif ".CSV" in file_path.upper():
        ext = ".csv"
    elif ".XLT" in file_path.upper():
        ext = ".xlt"
    elif ".zip" in file_path.upper():
        ext = ".zip"    
    else:
        ext = "N/A"



counts = 1
myZip = zipfile.ZipFile(path_to_zip_file)
print(myZip.namelist())

for file in myZip.filelist:
    if file.filename.endswith(".txt"):        # HERE HERE HERE HERE HERE HERE
        if os.path.basename(file.filename) in os.listdir(directory_to_extract_to):
            source = myZip.open(file)
            target = open(os.path.join(directory_to_extract_to, os.path.basename(file.filename).split(".")[0] + "_" + str(counts) + "." + os.path.basename(file.filename).split(".")[1]), "wb")
            counts = counts + 1 
            
        else:
            source = myZip.open(file)
            target = open(os.path.join(directory_to_extract_to, os.path.basename(file.filename)), "wb")

            with source, target:
                shutil.copyfileobj(source, target)
  • Don't know if I understand you correctly, but does this answer your question? [Check if string ends with one of the strings from a list](https://stackoverflow.com/questions/18351951/check-if-string-ends-with-one-of-the-strings-from-a-list) – Ocaso Protal Jul 30 '21 at 08:43
  • BTW: What will your `extention_finder` finder do with a filename like _Explanation of the .zip-File.txt_? – Ocaso Protal Jul 30 '21 at 08:46
  • Unfortunately, the solution you provided does not solve the problem. This code allows to extract the files with the extension in the "extension finder", but I can only extract the ".txt" ones because as you can see in the "HERE" section, it works with "endswith(.txt)". Including all of the following extensions found in the "extension finder" function, but doing this using the function. – Muratcan Çoban Jul 30 '21 at 08:56

1 Answers1

1

Assuming that the only . in the string file_path is the one that starts the file extension, this rewrite of your function should do the job:

def extension_finder(file_path):
    paths = ["XLSX", "XLS", "TXT", "CSV", "XLT", "ZIP"]
    return file_path.split(".")[1].upper() in paths

Then in the if statement you can call extension_finder with the path you want to check.

Robert Nixon
  • 190
  • 1
  • 1
  • 9