Python OS module learning notes
This article mainly introduces the study notes of the Python OS module. This article summarizes the common and practical methods of the OS module, and provides two examples. For more information, see
I. OS module Overview
The Python OS module contains common operating system functions. For example, copying, creating, modifying, and deleting files and folders...
Ii. Common Methods
1. OS. listdir () returns all files and directory names under the specified directory.
2. OS. remove () deletes an object.
3. Run the shell command in OS. system.
4. the OS. path. split () function returns the directory name and file name of a path.
5. the OS. path. isfile () and OS. path. isdir () functions verify whether the given path is a file or a directory. The returned values are true or False.
6. the OS. path. exists () function is used to check whether the given path exists. The return values are true or False, respectively.
7. OS. path. getsize (name) to get the file size. If the name is a directory, return 0L
8. OS. path. splitext () Separation of file names and extensions
9. OS. path. join (path, name) connection directory and file name or directory
10. OS. path. basename (path) returns the file name.
11. OS. path. dirname (path) returns the file path.
12. OS. walk (path)
This function returns a tuple with three elements representing the path name, directory list, and file list for each traversal.
Example of OS. walk:
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) # print the absolute path of the file
... For name in dirs:
... Print (OS. path. join (root, name) # print the absolute directory path...
Example: Use python to batch Modify file extensions:
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 ":
# Recombine the file name and suffix
Newname = portion [0] + ". dssp"
OS. rename (filename, newname)