Python file and file directory operation implementation code

Source: Internet
Author: User

I made some changes to the original text.

Features such as finding and deleting folders and files are implemented in the OS module. You need to pilot into this module when you use it,

The methods for importing are:

Import OS

First, get the current directory

s = OS.GETCWD ()

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

For example, if you are running abc.py, entering this command returns the location of the folder where ABC resides.

For a simple example, we put abc.py into a folder. And you want to create a new folder within folder A, regardless of where you put folder A 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", the equivalent of the doc command CD c:123

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

Exception type: Windowserror

Linux not to try, I do not know what kind of

Three breaks a path name into a directory name and a file name two parts

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

For example:

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

Print a

Print B

Show:

c:123456

Test.txt

Four decomposition file name extension

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

For example:

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

Print a

Print B

Show:

C:123456test

. txt

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


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

return value b:true or False

Vi. determining whether a path is a document

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

return value b:true or False

Vii. determine whether a path is a directory

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

return value b:true or False

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 ', ' t Est.txt ', ' WINDOWS ']

It's got both files and subdirectories.

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 the 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 ']

Nine, create a subdirectory

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

For example:

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

The call may fail, possibly because:

(1) When path already exists (whether it is a file or a folder)

(2) drive does not exist

(3) The disk is full

(4) disk is read-only or does not have write permission

X. Deleting subdirectories

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

Possible causes of an exception:

(1) path does not exist

(2) A file or subordinate subdirectory in the path subdirectory

(3) No permission to operate or read-only

When you test the function, you must first create a subdirectory.

Xi. Deletion of documents

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

Possible causes of an exception:

(1) filename does not exist

(2) The filename file, no permission to operate or read-only.

12. File name change

Os.name (Oldfilename, NewFileName)

Cause of the exception:

(1) oldfilename old filename does not exist

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

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.