Python standard library: os

os, as its name implies, is the standard library related to the operating system. Such as files, directories, executing system commands, etc.

1. Import module

os is a python standard library module. It can be installed with Python without separate installation and can be imported directly.

import os

2. path sub module

When it comes to disk file operations, the most commonly used module is the path module. Path is a sub module of OS. It can be used through from os import path or directly through the os.path attribute. In order to maintain consistency, this paper adopts the writing form of the latter.

2.1 exists(path)

Detect whether the file or directory exists. Returns True if it exists and False if it does not exist.

os.path.exists("dog.jpeg")
True

2.2 isfile(path)

Determine whether it is a file. Returns True, not False. It can also be used to determine whether the file exists.

os.path.isfile("dogs/")
False

2.3 isdir(path)

Determine whether it is a directory. Returns True, not False. It can also be used to determine whether a directory exists.

os.path.isdir("dogs/")
True

2.4 basename(path)

Returns the file name (including extension) that does not contain the directory.

os.path.basename("dir1/dir2/file.ext")
'file.ext'

2.5 dirname(path)

Returns the directory where the file is located.

os.path.dirname("dir1/dir2/file.ext")
'dir1/dir2'

2.6 split(path)

Returns a tuple. The first element of tuple is the directory where the file is located, and the second element is the file name (including extension). Equivalent to (dirname(path), basename(path)).

os.path.split("dir1/dir2/file.ext")
('dir1/dir2', 'file.ext')

2.7 splitext(path)

Returns a tuple. The first element of the tuple is the directory and file name of the file (without extension), and the second element is the extension (including.). Commonly used to read or change file extensions.

os.path.splitext("dir1/dir2/file.ext")
('dir1/dir2/file', '.ext')

2.8 join(path, *paths)

Splice different parts of the path into a complete path. Equivalent to os.sep.join([path, *paths]).

os.path.join("dir1", "dir2", "file.ext")
'dir1/dir2/file.ext'

2.9 getsize(path)

Returns the file size. Unit byte.

os.path.getsize("dog.jpeg")
18335

3. Directory operation

3.1 listdir(path='.')

Returns a list. The list is all files and subdirectories in the given directory, but does not contain special directories. And. The default is the current directory.

os.listdir("dogs")[:5]
['122.Pointer',
 '069.French_bulldog',
 '124.Poodle',
 '112.Nova_scotia_duck_tolling_retriever',
 '043.Canaan_dog']

3.2 mkdir(path, mode=0o777)

Create a directory named path. And specify directory permissions in numerical form. The default permission is 777.

os.mkdir("newdir")

3.3 makedirs(path, mode=0o777)

Create a directory with path recursively. And specify directory permissions in numerical form. The default permission is 777. It can be regarded as a more powerful mkdir. It will automatically create all parent directories of the leaf node directory. mkdir can only create the leaf node directory when the parent directory already exists.

os.makedirs("parent/child/newdir")

3.4 rmdir(path)

Delete directory. The directory must exist and only empty directories can be deleted. If it does not exist or is not empty, an exception will occur. To recursively delete the entire directory tree, use shutil.rmtree().

os.rmdir("newdir")

3.5 removedirs(path)

Recursively delete directories. The directory must exist and only empty directories can be deleted. If it does not exist or is not empty, an exception will occur. Different from rmdir, after deleting the leaf node directory, the parent directory will be deleted one by one until a directory that is not empty is encountered.

os.removedirs("parent/child/newdir")

3.6 remove(path)

Delete file. The directory cannot be deleted. The given path must be a file, otherwise an exception will occur.

# Copy file
with open("dog.jpeg", "rb") as f:
    content = f.read()
    with open("dog.copy.jpeg", "wb") as f2:
        f2.write(content)

# Delete file
os.remove("dog.copy.jpeg")

4. Other os interfaces

4.1 getenv(key, default=None)

Gets the environment variable.

os.getenv("PATH")
'/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin'

4.2 get_exec_path(env=None)

Returns a list of directories used to search for executable files. Look at it as a list of PATH environment variables.

os.get_exec_path()
['/usr/local/bin',
 '/usr/bin',
 '/bin',
 '/usr/sbin',
 '/sbin']

4.3 system(command)

In the current process, start the child process and execute the command (string). The main process will block until the execution of the child process is completed. This is achieved by calling the standard C function system() with the same restrictions.

if os.name == "nt":
    command = "dir"
else:
    command = "ls -l"

os.system(command)
0

Tags: Python Back-end

Posted on Wed, 20 Oct 2021 15:36:36 -0400 by clairence