Python 关联函数

Python associate function

我想将函数中找到的文件扩展名添加到我指定“HERE”的代码行中。换句话说,不仅是“.txt”,而且上述功能的扩展也应该被带到那部分。简而言之,我想将以下代码与功能相关联。

你能帮我吗?

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)

假设字符串 file_path 中唯一的 . 是开始文件扩展名的那个,你的函数的这个重写应该完成这项工作:

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

然后在if语句中你可以调用extension_finder你想检查的路径