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)
Advertisement
Answer
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.