Python study note 11: File Management in the standard library
1 OS package
The OS package includes a variety of functions to implement many features of the operating system. This package is very complex. Some commands of the OS package are used for file management.
Here we list the most commonly used:
Mkdir (path)
Create a new directory. The path is a string that represents the path of the new directory. Equivalent to the $ mkdir command
For example, we want to create a directory new:
import osos.mkdir('/home/Document/new')
Rmdir (path)
Delete an empty directory. The path is a string that indicates the path of the directory to be deleted. Equivalent to the $ rmdir command
Listdir (path)
Returns all files in the directory. Equivalent to the $ ls command.
Remove (path)
Delete the file pointed to by path.
Rename (src, dst)
Rename the file. src and dst are two paths, indicating the path before and after renaming, respectively.
Chmod (path, mode)
Change the permission of the file indicated by path. It is equivalent to the $ chmod command.
Chown (path, uid, gid)
Change the owner and owner Group of the file pointed to by path. Equivalent to the $ chown command.
Stat (path)
View the additional information of the file pointed to by path, which is equivalent to the $ ls-l command.
Symlink (src, dst)
Create a soft link for the file dst, and src is the path of the soft link file. Equivalent to the $ ln-s command.
Getcwd ()
Query the current working path (cwd, current working directory), equivalent to the $ pwd command.
2. shutil package
Copy (src, dst)
Copy the file from src to dst. Equivalent to the $ cp command.
Move (src, dst)
Move the file from src to dst. Equivalent to the $ mv command.
For example, we want to copy the.txt file:
import shutilshutil.copy('a.txt', 'b.txt')
The above functions are very similar to shell commands in Linux. Users familiar with Linux can understand them at a glance.