如何使用Python检查是否存在具有不同扩展名的同名文件

lpk*_*kej 3 python file pathlib

我对文件和当前编写方法相当陌生,我可以通过 file.pom 路径并检查 .jar 文件是否存在于同一路径中。

def get_file_type(self, file_path):
    return pathlib.Path(file_path).suffix

def check_if_file_exists(self, pom_file_path, extension):
    pom_file_extract_file = str(pom_file_path).rpartition("/")
    pom_file_extract_filename = str(pom_file_extract_file [-1]).rpartition("-")
    if pom_file_extract_filename ... # stuck

....

for file in files:
    f = os.path.join(zip_path, file)
        f_fixed = "." + f.replace("\\", "/")
        if self.get_file_type(f_fixed) == ".pom":
            pom_paths = (root + "/" + file).replace("\\", "/")
            print(pom_paths)

            # if self.check_if_file_exists(pom_paths, ".jar") == True:
            #     Do stuff...
Run Code Online (Sandbox Code Playgroud)

我应该通过pom的目​​录吗?

Jac*_*din 5

pathlib 为此有一些方便的功能:

from pathlib import Path

p = Path('./file.pom')

p.with_suffix('.jar').exists()
Run Code Online (Sandbox Code Playgroud)

您的功能将是:

def check_if_file_exists(self, pom_file_path, extension):
    return pom_file_path.with_suffix(extension).exists()
Run Code Online (Sandbox Code Playgroud)