Operations on Python folders and files (recommended ),

Source: Internet
Author: User

Operations on Python folders and files (recommended ),

Recently, programs are frequently written to deal with file operations. This is relatively weak, so you can find a good article on Baidu. This is the original article portal, I made some changes to the original article.

You can find and delete folders and files inOSModule. Before using this module,

The import method is as follows:

Import OS

1. Obtain the current directory

S =OS. getcwd ()

# The current directory (folder) is saved in s)

For example, to run abc. py, enter this command and return the location of the folder where abc is located.

For example, we put abc. py in the folder. In addition, you can create A new folder in folder A regardless of the location of folder A on the hard disk. The folder name is automatically generated based on the 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 ))

 

Ii. Change the current directory

OS. chdir ("C :\\ 123 ")

# Set the current directory to "C: \ 123", which is equivalent to cd c: \ 123 of the DOC command

# Note:If the specified directory does not exist, an exception is thrown.

Exception type: WindowsError

I didn't try it in Linux. I don't know which one it is.

 

3. Break a path name into two parts: Directory Name and file name.

Fpath, fname = OS. path. split ("path to be decomposed ")

For example:

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

Print

Print B

Display:

C :\ 123 \ 456

Test.txt

 

Iv. name extension of the decomposed File

Fpathandname, fext = OS. path. splitext ("path to be decomposed ")

For example:

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

Print

Print B

Display:

C: \ 123 \ 456 \ test

. Txt

 

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

 

B = OS. path. exists ("path to be determined ")

Return Value B: True or False

 

6. Determine whether a path is a file

B = OS. path. isfile ("path to be determined ")

Return Value B: True or False

 

7. Determine whether a path is a directory

B = OS. path. isdir ("path to be determined ")

Return Value B: True or False

 

8. Obtain the list of files and subdirectories in a directory

L = OS. listdir ("path to be determined ")

For example:

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

Print L

Display:

['1. avi ', '1.jpg', '1.txt ', 'config. SYS ', 'etpub', '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.

1. Obtain the 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 :\\")

Result:

['Documents and settings', 'downloads', 'htdzh ', 'kcbjgdjc', 'kcbjgdyb', 'kf _ GSSY_JC', 'msocac', 'program files ', 'python24', 'python31', 'qqvideo. cache ', 'recycler', 'System Volume information', 'tddownload', 'windows']

2. Obtain the list of all objects 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 :\\")

Result:

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

 

9. Create a subdirectory

OS. makedirs (path) # path is "subdirectory to be created"

For example:

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

The call may fail because:

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

(2) The drive does not exist

(3) The disk is full.

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

10. Delete sub-Directories

OS. rmdir (path) # path: "subdirectory to be deleted"

Possible causes of exceptions:

(1) path does not exist

(2) The path sub-directory contains files or sub-directories.

(3) No operation permission or read-only

When testing this function, create a subdirectory first.

11. Delete Files

OS. remove (filename) # filename: "name of the file to be deleted"

Possible causes of exceptions:

(1) filename does not exist

(2) You have no operation permission or read-only permission on the filename file.

12. File rename

OS. name (oldfileName, newFilename)

Cause of exception:

(1) The oldfilename old file name does not exist

(2) If a new newFilename file already exists, delete the newFilename file first.

The above Python folder and file-related operations (recommended) are all the content shared by the editor. I hope to give you a reference and support for the help house.

Related Article

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.