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.
--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ---------------
Always can't remember the API. Last night, when I wrote this, I didn't remember, so just sort it out:
The operation of files, folders (file manipulation functions) in Python involves both the OS module and the Shutil module.
Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()
Returns all files and directory names under the specified directory name: Os.listdir ()
function to delete a file: Os.remove ()
Delete multiple directories: Os.removedirs (r "C:\python")
Verifies whether the given path is a file: Os.path.isfile ()
Verify that the given path is a directory: Os.path.isdir ()
Determine if it is an absolute path: Os.path.isabs ()
Verify that the given path is really saved: os.path.exists ()
Returns the directory name and file name of a path: Os.path.split () eg os.path.split ('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/code ' , ' Poem.txt ')
Detach extension: Os.path.splitext ()
Get path name: Os.path.dirname ()
Get file name: Os.path.basename ()
Run shell command: Os.system ()
Read and SET Environment variables: os.getenv () and os.putenv ()
Gives the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
Indicates the platform you are using: Os.name for Windows, it is ' NT ', and for Linux/unix users, it is ' POSIX '
Rename: Os.rename (old, new)
Create a multilevel directory: Os.makedirs (r "C:\python\test")
Create a single directory: Os.mkdir ("Test")
Get file attributes: Os.stat (file)
Modify file permissions and timestamps: Os.chmod (file)
Terminate current process: Os.exit ()
Get File Size: os.path.getsize (filename)
File operation:
Os.mknod ("test.txt") Create an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if the file does not exist
About open mode:
W opens in write mode,
A opens in Append mode (starting with EOF and creating a new file if necessary)
R+ Open in read-write mode
w+ Open in read/write mode (see W)
A + opens in read/write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read/write mode (see r+)
Wb+ opens in binary read/write mode (see w+)
Ab+ opens in binary read/write mode (see A +)
Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character after Str
Fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.
Fp.close () #关闭文件. Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file
Fp.next () #返回下一行 and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.
Fp.seek (Offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file and is generally a positive number. However, if the whence parameter is provided, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.
Directory Operations:
Os.mkdir ("file") Create directory
To copy a file:
Shutil.copyfile ("Oldfile", "NewFile") Oldfile and NewFile can only be files
Shutil.copy ("Oldfile", "NewFile") Oldfile can only be a folder, NewFile can be a file, or it can be a destination directory
To copy a folder:
Shutil.copytree ("Olddir", "Newdir") Olddir and Newdir can only be directories, and newdir must not exist
Renaming files (directories)
Os.rename ("Oldname", "newname") files or directories are all using this command
Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
deleting files
Os.remove ("file")
Delete Directory
Os.rmdir ("dir") can only delete empty directories
Shutil.rmtree ("dir") empty directory, contents of the directory can be deleted
Converting catalogs
Os.chdir ("path") Change path
Related examples
1 Add ' _fc ' to all picture names under the folder
Python code:
#-*-Coding:utf-8-*-
Import re
Import OS
Import time
#str. Split (string) split string
# ' connectors '. Join (list) to make a list of strings
def change_name (path):
Global I
If not Os.path.isdir (path) and not Os.path.isfile (path):
Return False
If Os.path.isfile (path):
File_path = os.path.split (path) #分割出目录与文件
Lists = File_path[1].split ('. ') #分割出文件与文件扩展名
File_ext = lists[-1] #取出后缀名 (List slice operation)
Img_ext = [' bmp ', ' jpeg ', ' gif ', ' psd ', ' png ', ' jpg ']
If File_ext in Img_ext:
Os.rename (path,file_path[0]+ '/' +lists[0]+ ' _fc. +file_ext)
I+=1 #注意这里的i是一个陷阱
#或者
#img_ext = ' bmp|jpeg|gif|psd|png|jpg '
#if File_ext in Img_ext:
# print (' OK---' +file_ext)
Elif Os.path.isdir (PATH):
For x in Os.listdir (path):
Change_name (Os.path.join (path,x)) #os. Path.join () is useful in path processing
Img_dir = ' D:\\xx\\xx\\images '
Img_dir = img_dir.replace (' \ \ ', '/')
Start = Time.time ()
i = 0
Change_name (Img_dir)
c = Time.time ()-Start
Print (' program run time:%0.2f '% (c))
Print (' Total processed%s picture '% (i))
Output Result:
Program Run time: 0.11
Processed 109 pictures in total
Python file operations