This article mainly introduces Python commonly used file and file path, directory operation method Summary introduction, this article sets up the most commonly used file and directory operation functions, and describes their role, need friends can refer to the
Python's file and path manipulation functions are essentially in the OS and Os.path modules.
Os.listdir (dirname): Listing directories and files under DirName
Os.path.isdir (name): Determines if name is a directory, name is not a directory returns false
Os.path.isfile (name): Determines whether name is a file, does not exist name also returns false
OS.GETCWD (): Get current working directory
Os.path.split (name): Split file name and directory (in fact, if you completely use the directory, it will also put the last directory
Separate as a filename, and it does not determine whether a file or directory exists.
Os.path.splitext (): Detach file name and extension
Os.path.basename (PATH): Return file name
Os.path.dirname (path): Back to File path
Os.path.join (path,name): Connecting directories with file names or directories
You can use simple methods to match all subdirectories or files in a directory. Glob.glob (regression) returns a list
Os.listdir (dirname)
The function is equivalent to executing the dir command in the DirName directory, which returns a list. List of files and directories that do not include dirname
The code is as follows:
>>> Os.listdir ("D:/github")
[' about.html ', ' book ', ' en ', ' feiyuliu.github.com ', ' life ', ' pyssh ', ' Pythonstud
Y ', ' Studyshell ']
Where about.html is a file, feiyuliu.github.com is a directory.
Os.path.split (PATH)
Path is a route that returns a tuple and divides the path into two parts.
The code is as follows:
>>> os.path.split ("d:/github/about.html")
(' D:/github ', ' about.html ')
>>> os.path.split ("about.html")
(', ' about.html ')
Os.path.splitext (filename)
Divide the file into file name path and extension. Returns a tuple.
The code is as follows:
>>> os.path.splitext ("about.html")
(' About ', '. html ')
>>> os.path.splitext ("d:/github/about.html")
(' D:/github/about ', '. html ')
Os.path.dirname (PATH)
The directory output, do not output file name. Returns the string type.
The code is as follows:
>>> os.path.dirname ("d:/github/about.html")
' D:/github '
>>> os.path.dirname ("about.html")
' #输出为空
Os.path.basename (filename)
Gets the file name. return String type
The code is as follows:
>>> os.path.basename ("d:/github/about.html")
' About.html ' #注意不包括目录