This article mainly introduces Python's methods for traversing specified files and folders, and compares the two implementation techniques to analyze Python's methods for traversing files and folders, for more information about how to use Python to traverse specified files and folders, see the following example. Share it with you for your reference. The details are as follows:
Initial writing:
import osdef searchdir(arg,dirname,names): for filespath in names: open ('c:\\test.txt','a').write('%s\r\n'%(os.path.join(dirname,filespath))) if __name__=="__main__": paths="g:\\" os.path.walk(paths,searchdir,())
Modified and added file attributes.
#-*-Coding: cp936-*-import OS, time # change the time in the file attribute to '2017-1-12 00:00:00 format 'def formattime (localtime): endtime = time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime (localtime) return endtimedef searchdir (arg, dirname, names): for filespath in names: # obtain the file path fullpath = OS. path. join (dirname, filespath) # obtain the file attribute statinfo = OS. stat (fullpath) # file size sizefile = statinfo. st_size # Creation time creattime = formattime (statinfo. st_ctime) # modify time maketime = formattime (statinfo. st_mtime) # browse time readtime = formattime (statinfo. st_atime) # determine whether it is a folder or a file if OS. path. isdir (fullpath): filestat = 'dir' else: filestat = 'file' open ('C: \ test.txt ', 'A '). write ('[% s] path: % s file size (B): % s creation Time: % s Modification time: % s browsing time: % s \ r \ n' % (filestat, fullpath, sizefile, creattime, maketime, readtime) if _ name __= = "_ main __": paths = "g :\\" OS. path. walk (paths, searchdir ,())
I hope this article will help you with Python programming.