Introduction to the basic module of python os

os/sys module

os module:

Execute the following code:

import os

print(dir(os))

The results are as follows:

['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 
'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 
'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 
'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 
'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_AddedDllDirectory', 
'_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', 
'__loader__', '__name__', '__package__', '__spec__', '_check_methods', 
'_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', 
'_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'add_dll_directory', 
'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 
'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 
'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 
'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 
'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 
'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 
'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 
'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 
'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 
'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 
'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 
'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 
'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 
'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 
'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 
'urandom', 'utime', 'waitpid', 'walk', 'write']

Introduce the commonly used magic methods. I won't introduce them for the time being

  1. listdir()

    • Explanation: get the specified folder and view all documents and directories. The return value is list
    • Use: print(os.listdir("path")
  2. chdir()

    • Explanation: change directory function
    • os.chdir('path ')
  3. getcwd()

    • Explanation: view the current directory
    • print(os.getcwd())
  4. mkdir()

    • Explanation: create a folder, create a single (file path, permission)
    • os.mkdir("path", permission) is optional
  5. makedirs()

    • Explanation: create multiple folders at one time, recursively
    • os.makedir("path")
  6. rmdir() remove()

    • Explanation: you can delete only one folder at a time
    • Delete file
    • os.rmdir("path")
  • os.remove("remove")
  1. removedirs()

    • Explanation: delete empty files at one time
    • os.removedir("path")
  2. rename()

    • Explanation: change file name
    • os.rename("file name")
  3. stat()

    • Explanation: get file or folder status information
    • os.stat("path")
  4. system()

    • j explanation: execute the operating system command, use it with caution, and delete the system accidentally
    • os.system("command")
    • os.system("ping g.cn")
  5. getenv()

    • Get system variables directly, with return value
    • Set python system variable
    • os.getenv("Path")
    • os.getenv("path", "path")
  6. environ()

    • Specifically used to handle environment variables in python
    • Get environment variables without parameters
    • Add environment variable
    • os.environ["path"]
    • os.environ[Path]=r"c:\user\desktop"
  7. curdir()

    • Get the current folder path (relative path)
    • os.curdir
  8. pardir()

    • Get the folder path of the upper layer (relative path)
    • os.pardir
  9. path

    • This is a sub module of the os module, with a lot of content
    • os.path
  10. sep()

    • Gets the delimiter of the current system \ win / Linux or Unix \r \n
    • print(os.sep)
  11. extsep()

    • Gets the separator between the file name and the file suffix name
    • All operating systems are
    • print(os.extsep)
  12. print(os.name) to view

    nt stands for win system

    POSIX stands for Linux or Unix

  13. linesep()

    • Gets the line break of the system
    • print(os.linesep)
    • print(repr(os.linesep)) view missing characters \ r \n
  14. abspath()

    • Convert relative path to absolute path
    • os.path.abspath("path")
  15. basename()

    • Get the main part of the path, which is the file name
    • os.path.basename("path")
  16. dirname()

    • Get the path part of the path, except for the file name
    • os.path.dirname("path")
  17. isdir(), isfile(), islink()

    • Determine whether it is a folder
    • Determine whether it is a file
    • Determine whether it is a link
    • os.path.isdir("path")
    • os.path.isfile("path")
    • os.path.isink("path")
  18. join()

    • Splice the two paths together, one is the path and the other is the file

    • path1, path2

    • os.path.join(path1,path2)

  19. split()

    • Disassemble into two parts, one is the path and the other is the file name
    • os.path.split('path ')
  20. splitext()

    • The path search is divided into two parts, one is suffix and the other is other than suffix

    • os. path. Splittext ("path")

  21. getsize()

    • Get the file size, only judge the current file, and do not enter the next judgment
    • os.path.getsize("path")
  22. getctime, getmtime, getatime

    • Gets the creation time of the file
    • Get the modification time of the file
    • Gets the access time of the file
    • os. Path gettime ("path")
  23. exists()

    • Check whether the specified path exists
    • os.path.exists("path")
  24. isabs()

    • Determine whether the link is an absolute path
    • os.path.isabs("path")
  25. samefile()

    • Check whether the two paths point to the same folder
    • os.path.samefile("path")

sys module:

import sys
print(dir(sys))

The results are as follows:

['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', 
'__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
'__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', 
'_base_executable', '_clear_type_cache', '_current_frames', 
'_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', 
'_getframe', '_git', '_home', '_xoptions', 'addaudithook', 'api_version', 
'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright',
'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 
'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 
'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 
'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 
'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 
'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 
'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 
'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 
'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 
'pycache_prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 
'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 
'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'unraisablehook', 
'version', 'version_info', 'warnoptions', 'winver']

Common module methods are as follows:

  1. sys.argv

Realize the transfer of parameters from outside the program to the program.
sys.argv variable is a string list containing command line parameters, which are passed to the program through the command line Where the name of the script is always sys The first parameter in the argv list.

  1. sys.path

Contains a list of directory names for input modules.
Get the string set of the specified module search path. You can put the written module under a path, and you can find it correctly when importing in the program. Import module in import_ Name is based on sys Path to search for module Name, you can also add a custom module path.
sys.path.append("custom module path").

import sys
 
print("can you hear me?")
for i in sys.argv:
    print(i)
 
print("\n\nPython The path is:", sys.path, "\n")

result:

Python The path is: ['C:\\Users\\Chen Shao\\Desktop\\pycharm\\Python\\day41-50\\day49', 
'C:\\Users\\Chen Shao\\Desktop\\pycharm', 
'D:\\Pycharm2020.1\\plugins\\python\\helpers\\pycharm_display', 
'D:\\Python38\\python38.zip', 'D:\\Python38\\DLLs', 'D:\\Python38\\lib',
'D:\\Python38', 'C:\\Users\\Chen Shao\\AppData\\Roaming\\Python\\Python38\\site-
packages', 'D:\\Python38\\lib\\site-packages', 'D:\\Python38\\lib\\site-
packages\\win32', 'D:\\Python38\\lib\\site-packages\\win32\\lib', 
'D:\\Python38\\lib\\site-packages\\Pythonwin', 
'D:\\Pycharm2020.1\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] 
  1. sys.modules

sys.modules is a global dictionary, which is loaded into memory after Python is started. Whenever a programmer imports a new module, sys Modules will automatically record the module. When the module is imported for the second time, python will directly look it up in the dictionary, which speeds up the running speed of the program. It has all the methods that a dictionary has

import sys

def exitfunc(value):
    print(value)
    sys.exit(0)  # Normal exit
 
print('--------------')
try:
    sys.exit(1)
except SystemExit as value:
    exitfunc(value)
 
print("test")  # The program is over. You can't go here
--------------
1

Process finished with exit code 0
  1. sys.modules

sys.modules is a global dictionary, which is loaded into memory after Python is started. Whenever a programmer imports a new module, sys Modules will automatically record the module. When the module is imported for the second time, python will directly look it up in the dictionary, which speeds up the running speed of the program. It has all the methods that a dictionary has.

  1. sys.stdin/sys.stdout/sys.stderr

Stdin, stdout and stderr are file attribute objects in Python. When Python starts, they are automatically related to standard input, output and errors in the shell environment. The I/O redirection of Python program in the shell is provided by the shell, which has nothing to do with Python itself. The python program redirects the read and write operations of stdin, stdout and stderr to an internal object.

  • sys.stdin
import sys
 
print("Hello,%s" % input("Please enter your name:"))
print("-----------LINE--------------")
print("Please enter your name:")
name = sys.stdin.readline()[:-1]
print("Hello,%s" % name)
  • sys.stdout
import sys
 
print("This is standard output!")
sys.stdout.write("This is using sys output")

Note sys Stdout output ends without line wrapping, and end = '\n' cannot be used to force line wrapping.

  • sys.stderr
import sys
 
for i in (sys.stdin, sys.stdout, sys.stderr):
    print(i)

result:

<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>

Tags: Python

Posted by itazev on Fri, 13 May 2022 14:49:45 +0300