Python's way of traversing the specified files and folders

Source: Internet
Author: User
Tags file size

This article mainly introduces Python traversal of the specified file and folder methods, compared to the two implementation techniques to analyze the Python traversal file and folder methods, the need for friends can refer to the

Initial writing:


1 2 3 4 5 6 7 Import os def searchdir (arg,dirname,names): For Filespath in Names:open (' C:test.txt ', ' a '). Write ('%SRN '% ( Dirname,filespath)) If __name__== "__main__": paths= "G:" Os.path.walk (Paths,searchdir, ())

Made changes, added file attributes


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The -*-coding:cp936-*-import os,time #将文件属性中的时间改为 ' 2011 -1-12 00:00:00 format ' def formattime (localtime): Endtime=time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (localtime)) Return Endtime def searchdir (arg,dirname,names): For Filespath in Names: #得到文件路径 Fullpath=os.path.join (DirName, Filespath) #得到文件属性 Statinfo=os.stat (fullpath) #文件大小 sizefile=statinfo.st_size #创建时间 creattime=formattime ( _ctime) #修改时间 maketime=formattime (statinfo.st_mtime) #浏览时间 readtime=formattime (statinfo.st_atime) #判断是文件夹还是文件 if Os.path.isdir (fullpath): filestat= ' DIR ' else:filestat= ' file ' open (' c:test.txt ', ' a '). Write ('%s ' path:%s file size (B):%s Date Created:%s Modified:%s Browse time:%SRN '% (filestat,fullpath,sizefile,creattime,maketime,readtime)) if __name__== "__main__": Paths = "G:" Os.path.walk (Paths,searchdir, ())

I hope this article will help you with your Python programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.