6

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.

Leon
  • 31,443
  • 4
  • 72
  • 97
null_value28
  • 63
  • 1
  • 1
  • 4

4 Answers4

10

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.

Community
  • 1
  • 1
Jaimin Ajmeri
  • 572
  • 3
  • 18
2

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

Sam Marinelli
  • 999
  • 1
  • 6
  • 16
1

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

Chanda Korat
  • 2,453
  • 2
  • 19
  • 23
0

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)]
Amorpheuses
  • 1,403
  • 1
  • 9
  • 13