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

2024-04-25 11:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个相当新的文件和目前的写作方法,我可以通过文件.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...

我应该通过pom的dir吗?你知道吗


Tags: 文件pathself路径getifdefcheck
2条回答

在pathlib中找到了is_file()方法,使用该方法可以帮助我解决问题:

def check_if_file_exists(self, pom_file_path, extension):
    pom_file_path_one = str(pom_file_path).rpartition("/")
    pom_file_path_two = str(pom_file_path_one[-1]).rpartition(".")
    extension_file = pathlib.Path(pom_file_path_one[0] + "/" + pom_file_path_two[0] + extension)
    if extension_file.is_file():
        return True
    else:
        return False

编辑

尽管如此,我还是使用这个方法来查找-javadoc.jar文件。你知道吗

^{}有几个方便的函数:

from pathlib import Path

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

p.with_suffix('.jar').exists()

你的职能是:

def check_if_file_exists(self, pom_file_path, extension):
    return pom_file_path.with_suffix(extension).exists()

相关问题 更多 >

    热门问题