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