Op Thursday 4 Jun 2015 22:13 CEST schreef random: > On Tue, Jun 2, 2015, at 12:13, Cecil Westerhof wrote: >> I am thinking about using ipython3 instead of bash. When I want to >> find a file I can do the following: >> !find ~ -iname '*python*.pdf' >> but is there a python way? > > Python really isn't a good substitute for a shell, but the normal > python way to do this task is: > > import os, os.path, fnmatch > > home = os.path.expanduser('~') # only needed since you used ~ > for dirpath, dirnames, filenames in os.walk(home): > print(dirpath) > for filename in filenames: > if(fnmatch.fnmatch(filename.lower(), '*python*.pdf')): > print(os.path.join(dirpath, filename))
I was already thinking along those lines. I made it: def find(directory, to_match): to_match = to_match.lower() results = [] for dirpath, dirnames, filenames in os.walk(expanduser(directory)): for filename in filenames: if(fnmatch(filename.lower(), to_match)): results.append(os.path.join(dirpath, filename)) return results > Note that if you have filenames with invalid unicode characters (or > any non-ASCII characters at all on Windows) you may have to do > additional processing to the filename before printing it. And of > course instead of printing it you may want to store the filenames in > a list for further processing. But these are the basic building > blocks. I have to look into it further. For one thing default the match should be case dependent and an option used to make it independent. > I don't use ipython, so I don't know what it provides if anything to > make any of this easier. I think it is useful to have it in Python also, so I should not use ipython specific things. In ‘~/.ipython/profile_default/startup/00-init.ipy’ I have: from utilDecebal import find and now ‘find('~', '*Python*.pdf')’ gives what I want. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list