null_value28
null_value28

Reputation: 73

How to check if a file exists without looking at its extension name in 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.

Upvotes: 7

Views: 16616

Answers (4)

Chanda Korat
Chanda Korat

Reputation: 2561

You can use fnmatch also,

import os
import fnmatch

print filter(lambda f: fnmatch.fnmatch(f, "Filename.*"), os.listdir(FilePath))

Here, No need to format FilePath. You can simply write like 'C:\Python27\python.*'

Upvotes: 1

Amorpheuses
Amorpheuses

Reputation: 1423

This will get all the files with the basename you want (in this case 'tmp') with or without an extension and will exclude things that start with your basename - like tmp_tmp.txt for example:

import re
import os

basename='tmp'
for filename in os.listdir('.'):
  if re.match(basename+"(\..*)?$", filename):
     print("this file: %s matches my basename"%filename)

Or of course if you prefer them in a list, more succinctly:

[fn for fn in os.listdir('.') if re.match(basename+"(\..*)?$",fn)]

Upvotes: 0

Sam Marinelli
Sam Marinelli

Reputation: 1119

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

Upvotes: 2

Jaimin Ajmeri
Jaimin Ajmeri

Reputation: 602

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.

Upvotes: 13

Related Questions