Python folder and file operation implementation code

Source: Internet
Author: User
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 to find and delete folders and files, and other functions are implemented in the OS module. 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 osimport timefolder = 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: An exception is thrown when the specified directory does not exist.
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 bprint  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 bprint  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.

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.