
废话不多说,先上程序
import os,easygui import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() text_int = 0 cache = open('查找缓存','w') cache.truncate() cache.close() cache = open('查找缓存','a+') # cache.write('\n123456') # cache.write('\n78910') # cache.seek(0,0) # easygui.msgbox(msg=cache.read()) easygui.msgbox(title='提示~~~',ok_button="Go Go Go!!!",msg='输入格式:\n 1. name:文件名(文件名是你要查找的文件,‘name:’不动。)' '\n 2. suffix:后缀名(后缀名是你要查找的文件的后缀名,‘suffix:’不动。)' '\n内置用法:' '\n 1. all : 输出该文件下所有文件及子文件名' '\n默认为第一种格式!!!' '\n文字全部为英文表达!!!') while True: try: enter = easygui.enterbox(msg='输入你要查找的文件') if len(enter) != 0: path = filedialog.askdirectory() #获得选好的文件夹 files = [] def get_filelist(dir): Filelist = [] for home, dirs, files in os.walk(path): for filename in files: # 文件名列表,包含完整路径 Filelist.append(os.path.join(home, filename)) # # 文件名列表,只包含文件名 # Filelist.append( filename) return Filelist if __name__ == "__main__": Filelist = get_filelist(dir) for file in Filelist: #files.append(file) f = file.split('\\')[-1].split('.')[0] f2 = file.split('\\')[-1].split('.')[-1] enter_l = enter.split(':') if enter != 'all': if enter_l[0] == 'name': if enter_l[-1] == f: cache.write('\n'+file) break else: if enter_l[-1] in f: cache.write('\n'+file) elif enter_l[0] == 'suffix': if str.upper(enter_l[-1]) == str.upper(f2): cache.write('\n'+file) else: if enter_l[-1] == f: cache.write('\n'+file) break else: if enter_l[-1] in f: cache.write('\n'+file) else: cache.write('\n'+f+'---'+file) break else: break except Exception as e: easygui.msgbox(title='Error',msg=str(e)) text_int = 1 break if text_int == 0: cache.seek(0,0) easygui.msgbox(msg=cache.read(),ok_button='退出') cache.close()
程序全解:
模块:
窗口(用到):
tk.Tk()
class Tk(Misc, Wm): """Toplevel widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter.""" _w = '.' def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" self.master = None self.children = {} self._tkloaded = False # to avoid recursions in the getattr code in case of failure, we # ensure that self.tk is always _something_. self.tk = None if baseName is None: import os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc'): baseName = baseName + ext interactive = 0 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) if useTk: self._loadtk() if not sys.flags.ignore_environment: # Issue #16248: Honor the -E flag to avoid code injection. self.readprofile(baseName, className) def loadtk(self): if not self._tkloaded: self.tk.loadtk() self._loadtk() def _loadtk(self): self._tkloaded = True global _default_root # Version sanity checks tk_version = self.tk.getvar('tk_version') if tk_version != _tkinter.TK_VERSION: raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" % (_tkinter.TK_VERSION, tk_version)) # Under unknown circumstances, tcl_version gets coerced to float tcl_version = str(self.tk.getvar('tcl_version')) if tcl_version != _tkinter.TCL_VERSION: raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \ % (_tkinter.TCL_VERSION, tcl_version)) # Create and register the tkerror and exit commands # We need to inline parts of _register here, _ register # would register differently-named commands. if self._tclCommands is None: self._tclCommands = [] self.tk.createcommand('tkerror', _tkerror) self.tk.createcommand('exit', _exit) self._tclCommands.append('tkerror') self._tclCommands.append('exit') if _support_default_root and not _default_root: _default_root = self self.protocol("WM_DELETE_WINDOW", self.destroy) def destroy(self): """Destroy this and all descendants widgets. This will end the application of this Tcl interpreter.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) Misc.destroy(self) global _default_root if _support_default_root and _default_root is self: _default_root = None def readprofile(self, baseName, className): """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into the Tcl Interpreter and calls exec on the contents of BASENAME.py and CLASSNAME.py if such a file exists in the home directory.""" import os if 'HOME' in os.environ: home = os.environ['HOME'] else: home = os.curdir class_tcl = os.path.join(home, '.%s.tcl' % className) class_py = os.path.join(home, '.%s.py' % className) base_tcl = os.path.join(home, '.%s.tcl' % baseName) base_py = os.path.join(home, '.%s.py' % baseName) dir = {'self': self} exec('from tkinter import *', dir) if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): exec(open(class_py).read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): exec(open(base_py).read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. Applications may want to override this internal function, and should when sys.stderr is None.""" import traceback print("Exception in Tkinter callback", file=sys.stderr) sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb) def __getattr__(self, attr): "Delegate attribute access to the interpreter object" return getattr(self.tk, attr) # Ideally, the classes Pack, Place and Grid disappear, the # pack/place/grid methods are defined on the Widget class, and # everybody uses w.pack_whatever(...) instead of Pack.whatever(w, # ...), with pack(), place() and grid() being short for # pack_configure(), place_configure() and grid_columnconfigure(), and # forget() being short for pack_forget(). As a practical matter, I'm # afraid that there is too much code out there that may be using the # Pack, Place or Grid class, so I leave them intact -- but only as # backwards compatibility features. Also note that those methods that # take a master as argument (e.g. pack_propagate) have been moved to # the Misc class (which now incorporates all methods common between # toplevel and interior widgets). Again, for compatibility, these are # copied into the Pack, Place or Grid class. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0): return Tk(screenName, baseName, className, useTk) ----- 创建窗口实例
filedialog.askdirectory()
def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() ----- 获得选好的文件夹(tkinter)
easygui.msgbox()
def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK", image=None, root=None): ------创建提示窗口
easygui.enterbox()
def enterbox(msg="Enter something.", title=" ", default="", strip=True, image=None, root=None): ----- 创建输入窗口
文件操作:
open()
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open """ Open file and return a stream. Raise OSError upon failure. file is either a text or byte string giving the name (and the path if the file isn't in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for creating and writing to a new file, and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists. Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn't. Files opened in binary mode (appending 'b' to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. 'U' mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode. buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device's "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`. On many systems, the buffer will typically be 4096 or 8192 bytes long. * "Interactive" text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files. encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings. errors is an optional string that specifies how encoding errors are to be handled---this argument should not be used in binary mode. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run 'help(codecs.Codec)' for a list of the permitted encoding error strings. newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case. A custom opener can be used by passing a callable as *opener*. The underlying file descriptor for the file object is then obtained by calling *opener* with (*file*, *flags*). *opener* must return an open file descriptor (passing os.open as *opener* results in functionality similar to passing None). open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode. """ pass
清空
cache.truncate()
关闭
cache.close()
写入
cache.write()
路径查找
def get_filelist(dir):
Filelist = []
for home, dirs, files in os.walk(path):
for filename in files:
# 文件名列表,包含完整路径
Filelist.append(os.path.join(home, filename))
# # 文件名列表,只包含文件名
# Filelist.append( filename)
return Filelist
path为要遍历的主文件夹
Filelist为该文件下所有文件及子文件名
报错判断
try:
*&……¥%##¥%
expent:
)(*&^%$#$%^&*(

2274





