Python folder and file manipulation ZZ

Source: Internet
Author: User
Tags explode

Recently wrote the program frequently dealing with file operations, this piece is weaker, but also in Baidu to find a good article, this is the original transmission door, I made some changes to the original text.

Features such as folder and file lookup, deletion, etc. are implemented in the OS module. The module should be piloted into the application,

The methods to import are:

Import OS

First, get the current directory

s = os.getcwd ()

# s is the current directory (that is, the folder)

For example, if you run abc.py, entering the command returns the folder location where the ABC is located.

For a simple example, we put abc.py into the a folder. And you can create a new folder within the A folder, regardless of where you put the a folder on your hard disk. and the name of the folder is automatically generated based on time.

Import OS

Import time

folder = Time.strftime (r "%y-%m-%d_%h-%m-%s", Time.localtime ())

Os.makedirs (R '%s/%s '% (OS.GETCWD (), folder))

Second, change the current directory

Os.chdir ("c:\\123")

#将当前目录设为 "C:\123", CD C:\123 equivalent to the doc command

#说明: throws an exception when the specified directory does not exist.

Exception type: Windowserror

Linux did not try, I do not know which kind of

Three decomposition of a pathname into a directory name and a file name two parts

Fpath, fname = Os.path.split ("The path you want to explode")

For example:

A, B = os.path.split ("C:\\123\\456\\test.txt")

Print a

Print B

Show:

c:\123\456

Test.txt

Quad-exploded file name extension

Fpathandname, fext = Os.path.splitext ("The path you want to explode")

For example:

A, B = os.path.splitext ("C:\\123\\456\\test.txt")

Print a

Print B

Show:

C:\123\456\test

. txt

V. Determine if a path (directory or file) exists

b = os.path.exists ("The path you want to judge")

return value b:true or False

VI. Determine if a path is a file

b = Os.path.isfile ("The path you want to judge")

return value b:true or False

Seven, determine whether a path directory

b = Os.path.isdir ("The path you want to judge")

return value b:true or False

Viii. get a list of files and subdirectories in a directory

L = Os.listdir ("The path you want to judge")

For example:

L = Os.listdir ("c:/")

Print L

Show:

[' 1.avi ', ' 1.jpg ', ' 1.txt ', ' CONFIG. SYS ', ' inetpub ', ' IO. SYS ', ' KCBJGDJC ', ' kcbjgdyb ', ' kf_gssy_jc ', ' MSDOS. SYS ', ' MSOCache ', ' ntdetect.com ', ' ntldr ', ' Pagefile.sys ', ' pdoxusrs.net ', ' program Files ', ' Python24 ', ' Python31 ', ' Qqvideo.cache ', ' recycler ', ' System Volume information ', ' tddownload ', ' test.txt ', ' WINDOWS ']

There are both files and subdirectories in it.

1 Get a list of all subdirectories under a specified directory

def getdirlist (P):

p = str (P)

If p== "":

return []

p = p.replace ("/", "\ \")

If p[-1]! = "\ \":

p = p+ "\ \"

A = Os.listdir (p)

b = [x for x in a If Os.path.isdir (p + x)]

Return b

Print getdirlist ("c:\\")

Results:

[' Documents and Settings ', ' Downloads ', ' Htdzh ', ' KCBJGDJC ', ' kcbjgdyb ', ' kf_gssy_jc ', ' MSOCache ', ' program Files ', ' Pyth On24 ', ' Python31 ', ' qqvideo.cache ', ' recycler ', ' System Volume information ', ' tddownload ', ' WINDOWS ']

2 Get a list of all files in a specified directory

def getfilelist (P):

p = str (P)

If p== "":

return []

p = p.replace ("/", "\ \")

If p[-1]! = "\ \":

p = p+ "\ \"

A = Os.listdir (p)

b = [x for x in a If os.path.isfile (p + x)]

Return b

Print getfilelist ("c:\\")

Results:

[' 1.avi ', ' 1.jpg ', ' 1.txt ', ' 123.txt ', ' 12345.txt ', ' 2.avi ', ' a.py ', ' AUTOEXEC '. BAT ', ' boot. ini ', ' bootfont.bin ', ' CONFIG '. SYS ', ' IO. SYS ', ' MSDOS. SYS ', ' ntdetect.com ', ' ntldr ', ' Pagefile.sys ', ' pdoxusrs.net ', ' test.txt ']

Ix. Creating subdirectories

Os.makedirs (path) # path is "subdirectory to create"

For example:

Os.makedirs ("c:\\123\\456\\789")

The invocation may fail, possibly due to:

(1) When path already exists (either file or folder)

(2) drive does not exist

(3) The disk is full

(4) The disk is read-only or has no write permission

X. Delete subdirectories

Os.rmdir (PATH) # path: "Subdirectories to delete"

Possible causes of an exception:

(1) path does not exist

(2) The path subdirectory has a file or sub-directory

(3) No operational permissions or read-only

When you test the function, make a subdirectory from the first.

Xi. Deleting files

Os.remove (filename) # filename: "File name to delete"

Possible causes of an exception:

(1) filename does not exist

(2) The filename file has no operational permissions or is read-only.

12. File name change

Os.name (Oldfilename, NewFileName)

Cause of the exception:

(1) Oldfilename old file name does not exist

(2) NewFileName The new file already exists, you need to delete the NewFileName file first.

------------------------------------------------------------------------------------------------------------

Http://www.cnblogs.com/yuxc/archive/2011/08/01/2124012.html

Python folder and file manipulation ZZ

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.