This article mainly introduces the Python OS module learning notes, this article summarizes the OS module common methods, practical methods, and gave two examples of use, the need for friends can refer to the
I. Overview of OS Modules
The Python OS module contains universal operating system capabilities. For example, file copying, creating, modifying, deleting files and folders ...
Ii. Common methods
1, Os.listdir () returns all the file and directory names under the specified directory.
2, Os.remove () delete a file.
3, Os.system () run the shell command.
4. The Os.path.split () function returns the directory name and filename of a path
5. The Os.path.isfile () and the Os.path.isdir () function respectively verify that the path given is a file or a directory, and that the return value is Ture or FALSE, respectively.
6, the os.path.exists () function is used to verify that the given path exists, and that the return value is Ture or false.
7, Os.path.getsize (name) to get the file size, if name is directory return 0L
8, Os.path.splitext () separate file name and extension
9, Os.path.join (path,name) connection directory and file name or directory
10, Os.path.basename (path) return file name
11, Os.path.dirname (path) return file path
12, Os.walk (PATH)
The function returns a tuple that has 3 elements, each representing the pathname of each traversal, the directory list, and the file list
Os.walk () For example:
The code is as follows:
>>> Import OS
>>> for Root, dirs, files in Os.walk ("Wd/chat", Topdown=false):
... for name in files:
... print (Os.path.join (root, name)) #打印文件绝对路径
... for name in dirs:
... print (Os.path.join (root, name)) #打印目录绝对路径 ...
Instance: Batch modification of file extensions with Python:
The code is as follows:
Import OS
# list all files in the current directory
Files = Os.listdir (".")
For filename in Files:
Portion = os.path.splitext (filename)
# if the suffix is. txt
If portion[1] = = ". pdb":
# Regroup file names and suffix names
newname = portion[0] + ". Dssp"
Os.rename (Filename,newname)