Python folder and file operation implementation code _python

Source: Internet
Author: User

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:\123\456
Test.txt

Four name extension of the exploded file name

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:\123\456\test
. txt

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

B = os.path.exists ("Path you want to judge")
returns the value b:true or False
 
Six, determining whether a path is a file
B = Os.path.isfi Le ("path you want to judge")
return value b:true or False
 
Seven, determine if a path is a directory
b = Os.path.isdir ("Path you want to judge")
Return return value b:true or False
 
Eight, get a list of files and subdirectories in a directory         
L = Os.listdir ("Path you want to judge")
For example:
L = Os.listdir ("c:/")
Print L
Displays:
[' 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 '
This contains both files and subdirectories
1 gets 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 on a If Os.path.isdir (P + x)] return
    b
print  g Etdirlist ("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 on a If os.path.isfile (P + x)] return
    b
p Rint  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)
causes an exception:
(1) oldfilename the old file name does not exist
(2) newfilename The new file already exists, you need to first delete NewFileName files.

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.