Python traversal of specified files and folders-Python tutorial

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.