I. Overview of OS modules
The Python OS module contains common operating system features. For example, copying, creating, modifying, deleting files and folders ...
Second, common methods
1, Os.listdir () returns all 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 file name of a path
5, Os.path.isfile () and Os.path.isdir () function respectively check whether the given path is a file or directory, the return value is Ture or false
6. The os.path.exists () function is used to verify that the given path exists and that the return value is Ture or FALSE, respectively.
7, Os.path.getsize (name) get file size, if name is directory return 0L
8. Os.path.splitext () detach file name and extension
9. Os.path.join (path,name) connection directory with file name or directory
10. Os.path.basename (path) returns the file name
11, Os.path.dirname (path) return file path
12, Os.walk (PATH)
The function returns a tuple that has 3 elements, each of which represents the path name of each traversal, the directory list, and the file list.
Os.walk () 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)) #打印目录绝对路径 ...
Example: Batch modification of file extensions with Python:
The code is as follows:
Import OS
# list all the 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)