Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists without looking at its extension name in Python?

Tags:

python

A file can have multiple extensions but name of the file will remains same. I have tried

import os.path
os.path.isfile("Filename")

but this code is looking at the extension of the file also.

like image 609
null_value28 Avatar asked Feb 10 '17 06:02

null_value28


2 Answers

This would list all files with same name but different extensions.

import glob
print glob.glob("E:\\Logs\\Filename.*")

You could use this check instead.

import glob
if glob.glob("E:\\Logs\\Filename.*"):
    print "Found"

Refer this post.

like image 69
Jaimin Ajmeri Avatar answered Oct 10 '22 04:10

Jaimin Ajmeri


Try this.

import os

def check_file(dir, prefix):
    for s in os.listdir(dir):
        if os.path.splitext(s)[0] == prefix and os.path.isfile(os.path.join(dir, s)):
            return True

    return False

You can call this function like, e.g., check_file("/path/to/dir", "my_file") to search for files of the form /path/to/dir/my_file.*.

like image 36
Sam Marinelli Avatar answered Oct 10 '22 04:10

Sam Marinelli