简体   繁体   中英

How to check if file with same name exists with different extensions using Python

I'm fairly new with files and currently writing method where I could pass file.pom path and check if .jar files exists in the same path.

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...

Should I pass the dir of pom?

pathlib has a few convenient functions for this:

from pathlib import Path

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

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

Your function would then be:

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

Found in pathlib there is is_file() method, using that helped me to figure out my problem:

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

EDIT

Altough, I use this method for finding -javadoc.jar files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM