Python check if given filename exists code example
But your code is going to look something like this: It’s quite possible that what you get in the callback is actually a pointer to some kind of structure or list of structures you’re going to have to define—likely the same you’d need for calling the Nt/Zw functions directly, so let me show that as an example—if you get back a , not a , in the callback, it’s as simple as this: Solution 2: You could use a try/except block. check if a file is open in Python You need to either exclude reserved names or create an expression (regexp) matching the OS allowed filename domain, and test your filename against that, for each target platform. AFAIK, Python does not offer such helpers, because it’s Easier to Ask Forgiveness than Permission.
Validate a filename in python
You can enforce the user to create a file/directory inside wiki by normalizing the path with os.path.normpath and then checking if the path begins with say ‘(path-to-wiki)’
os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)')
To ensure that the user’s entered path/filename doesn’t contain anything nasty, you can force the user to enter a path or filename to either of Lower/Upper Alpha, Numeric Digits or may be hyphen or underscore.
Then you can always check the normalized filename using a similar regular expression
userpath=os.path.normpath('(path-to-wiki)/foo/bar.txt') re.findall(r'[^A-Za-z0-9_\-\\]',userpath)
if userpath=os.path.normpath(‘(path-to-wiki)/foo/bar.txt’) then
if not os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)') or re.search(r'[^A-Za-z0-9_\-\\]',userpath): . Do what ever you want with an invalid path
now there is a full library to validate strings : check it out:
from pathvalidate import sanitize_filepath fpath = "fi:l*e/p\"a?t>h|.t -> <>".format(fpath, sanitize_filepath(fpath))) fpath = "\0_a*b:ce%f/(g)h+i_0.txt" print("<> -> <>".format(fpath, sanitize_filepath(fpath)))
fi:l*e/p"a?t>h|.t file/path.txt _a*b:ce%f/(g)h+i_0.txt -> _abcde%f/(g)h+i_0.txt
Armin Ronacher has a blog post on this subject (and others).
These ideas are implemented as the safe_join() function in Flask:
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content. :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path would fall out of `directory`. """ filename = posixpath.normpath(filename) for sep in _os_alt_seps: if sep in filename: raise NotFound() if os.path.isabs(filename) or filename.startswith('../'): raise NotFound() return os.path.join(directory, filename)
Filenames — Checking file name with python, You can use split method and check if a file name repeats itself: import os present_files = [] # This will contain the unique file names for filename in os.listdir («eyeclosed»): if filename.endswith («.jpg») lookname = filename.split (‘_’) [0] #This is the part of the name you are looking for to repeat itself if lookname in …
Check if a filename is valid
The most harsh way to check if a file would be a valid filename on you target OSes is to check it against a list of properly tested filenames.
valid = myfilename in ['this_is_valid_name.jpg']
Expanding on that, you could define a set of characters that you know are allowed in filenames on every platform :
valid = set(valid_char_sequence).issuperset(myfilename)
But this is not going to be enough, as some OSes have reserved filenames.
You need to either exclude reserved names or create an expression (regexp) matching the OS allowed filename domain, and test your filename against that, for each target platform.
AFAIK, Python does not offer such helpers, because it’s Easier to Ask Forgiveness than Permission. There’s a lot of different possible combinations of OSes/filesystems, it’s easier to react appropriately when the os raises an exception than to check for a safe filename domain for all of them.
Python — Check if a filename is valid, The most harsh way to check if a file would be a valid filename on you target OSes is to check it against a list of properly tested filenames. valid = myfilename in [‘this_is_valid_name.jpg’] Expanding on that, you could define a set of characters that you know are allowed in filenames on every platform :
Python check if file exists in folder with name
import os file_exists = os.path.exists("example.txt") # Returns boolean representing whether or not the file exists
>>> import os >>> os.path.isfile("d:\\Package1\\package1\\fibo.py") True >>> os.path.isfile("d:/Package1/package1/fibo.py") True >>> os.path.isfile("d:\\nonexisting.txt")
Python search for filename pattern within a specific, From Python Docs. glob.glob(pathname) Return a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken …
In python how can i know a given file is being used
I’m not sure which of these two you want to find:
- Are there are any existing HANDLEs for a given file, like the handle and Process Explorer tools shows?
- Are there any existing locked HANDLEs for a given file, like the Unlocker tool shows.
But either way, the answer is similar.
Obviously it’s doable, or those tools couldn’t do it, right? Unfortunately, there is nothing in the Python stdlib that can help. So, how do you do it?
You will need to access Windows APIs functions—through pywin32 , ctypes , or otherwise.
There are two ways to go about it. The first, mucking about with the NT kernel object APIs, is much harder, and only really needed if you need to work with very old versions of Windows. The second, NtQuerySystemInformation , is the one you probably want.
The details are pretty complicated (and not well documented), but they’re explained in a CodeProject sample program and on the Sysinternals forums.
If you don’t understand the code on those pages, or how to call it from Python, you really shouldn’t be doing this. If you get the gist, but have questions, or get stuck, of course you can ask for help here (or at the sysinternals forums or elsewhere).
However, even if you have used ctypes for Windows before, there are a few caveats you may not know about:
Many of these functions either aren’t documented, or the documentation doesn’t tell you which DLL to find them in. They will all be in either ntdll or kernel32 ; in some cases, however, the documented NtFooBar name is just an alias for the real ZwFooBar function, so if you don’t find NtFooBar in either DLL, look for ZwFooBar .
At least on older versions of Windows, ZwQuerySystemInformation does not act as you’d expect: You cannot call it with a 0 SystemInformationLength , check the ReturnLength , allocate a buffer of that size, and try again. The only thing you can do is start with a buffer with enough room for, say, 8 handles, try that, see if you get an error STATUS_INFO_LENGTH_MISMATCH, increase that number 8, and try again until it succeeds (or fails with a different error). The code looks something like this (assuming you’ve defined the SYSTEM_HANDLE structure):
STATUS_INFO_LENGTH_MISMATCH = 0xc0000004 i = 8 while True: class SYSTEM_HANDLE_INFORMATION(Structure): _fields_ = [('HandleCount', c_ulong), ('Handles', SYSTEM_HANDLE * i)] buf = SYSTEM_HANDLE_INFORMATION() return_length = sizeof(buf) rc = ntdll.ZwQuerySystemInformation(SystemHandleInformation, buf, sizeof(buf), byref(return_length)) if rc == STATUS_INFO_LENGTH_MISMATCH: i += 8 continue elif rc == 0: return buf.Handles[:buf.HandleCount] else: raise SomeKindOfError(rc)
Finally, the documentation doesn’t really explain this anywhere, but the way to get from a HANDLE that you know is a file to a pathname is a bit convoluted. Just using NtQueryObject(ObjectNameInformation) returns you a kernel object space pathname, which you then have to map to either a DOS pathname, a possibly-UNC normal NT pathname, or a \?\ pathname. Of course the first doesn’t work files on network drives without a mapped drive letter; neither of the first two work for files with very long pathnames.
Of course there’s a simpler alternative: Just drive handle , Unlocker , or some other command-line tool via subprocess .
Or, somewhere in between, build the CodeProject project linked above and just open its DLL via ctypes and call its GetOpenedFiles method, and it will do the hard work for you.
Since the project builds a normal WinDLL-style DLL, you can call it in the normal ctypes way. If you’ve never used ctypes , the examples in the docs show you almost everything you need to know, but I’ll give some pseudocode to get you started.
First, we need to create an OF_CALLBACK type for the callback function you’re going to write, as described in Callback functions. Since the prototype for OF_CALLBACK is defined in a .h file that I can’t get to here, I’m just guessing at it; you’ll have to look at the real version and translate it yourself. But your code is going to look something like this:
from ctypes import windll, c_int, WINFUNCTYPE from ctypes.wintypes import LPCWSTR, UINT_PTR, HANDLE # assuming int (* OF_CALLBACK)(int, HANDLE, int, LPCWSTR, UINT_PTR) OF_CALLBACK = WINFUNCTYPE(c_int, HANDLE, c_int, LPWCSTR, UINT_PTR) def my_callback(handle, namelen, name, context): # do whatever you want with each handle, and whatever other args you get my_of_callback = OF_CALLBACK(my_callback) OpenFileFinder = windll.OpenFileFinder # Might be GetOpenedFilesW, as with most Microsoft DLLs, as explained in docs OpenFileFinder.GetOpenedFiles.argtypes = (LPCWSTR, c_int, OF_CALLBACK, UINT_PTR) OpenFileFinder.GetOpenedFiles.restype = None OpenFileFinder.GetOpenedFiles(ru'C:\Path\To\File\To\Check.txt', 0, my_of_callback, None)
It’s quite possible that what you get in the callback is actually a pointer to some kind of structure or list of structures you’re going to have to define—likely the same SYSTEM_HANDLE you’d need for calling the Nt/Zw functions directly, so let me show that as an example—if you get back a SYSTEM_HANDLE * , not a HANDLE , in the callback, it’s as simple as this:
class SYSTEM_HANDLE(Structure): _fields_ = [('dwProcessId', DWORD), ('bObjectType', BYTE), ('bFlags', BYTE), ('wValue', WORD), ('pAddress', PVOID), ('GrantedAccess', DWORD)] # assuming int (* OF_CALLBACK)(int, SYSTEM_HANDLE *, int, LPCWSTR, UINT_PTR) OF_CALLBACK = WINFUNCTYPE(c_int, POINTER(SYSTEM_HANDLE), c_int, LPWCSTR, UINT_PTR)
You could use a try/except block.
check if a file is open in Python
try: f = open("file.txt", "r") except IOError: print "This file is already in use"
How to check if a file is a directory or regular file in, How do you check if a path is a directory or file in python? An educational example from the stat documentation:. import os, sys from stat import * def walktree(top, callback): »’recursively descend the directory tree rooted at top, calling the callback function for each regular file»’ for f in os.listdir(top): …