Python traversal of specified files and folders

Source: Internet
Author: User

Python traversal of specified files and folders

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, see

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 (' % s \ r \ n' % (OS. path. join (dirname, filespath )))

If _ name __= = "_ main __":

Paths = "g :\\"

OS. path. walk (paths, searchdir ,())

Modified and 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

23

24

25

26

27

28

29

#-*-Coding: cp936 -*-

Import OS, time

# Change the time in the file attribute to '2017-1-12 00:00:00 formatting'

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:

# Obtain the file path

Fullpath = OS. path. join (dirname, filespath)

# Get File Attributes

Statinfo = OS. stat (fullpath)

# File Size

Sizefile = statinfo. st_size

# Creation Time

Creattime = formattime (statinfo. st_ctime)

# Modification time

Maketime = formattime (statinfo. st_mtime)

# Browsing time

Readtime = formattime (statinfo. st_atime)

# Determining whether a folder or a file is used

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.