Twenty-eight days of python learning (module)

Today's main content:

1.os module

2. Modules and methods of referencing modules

 

1. os module

The os module is the module that interacts with the operating system

The built-in methods are as follows:

os.getcwd() Get the current working directory, that is, the directory path where the current python script works
os.chdir( " dirname " ) changes the working directory of the current script; equivalent to cd under the shell
os.curdir returns the current directory: ( ' . ' )
os.pardir Get the parent directory string name of the current directory: ( ' .. ' )
os.makedirs( ' dirname1/dirname2 ' ) can generate multi-level recursive directories
os.removedirs( ' dirname1 ' ) If the directory is empty, delete it and recurse to the previous directory, if it is also empty, delete it, and so on
os.mkdir( ' dirname ' ) generates a single-level directory; equivalent to mkdir dirname in the shell
os.rmdir( ' dirname ' ) deletes a single-level empty directory. If the directory is not empty, it cannot be deleted, and an error is reported; it is equivalent to rmdir dirname in the shell
os.listdir( ' dirname ' ) lists all files and subdirectories in the specified directory, including hidden files, and prints them in a list
os.remove() removes a file
os.rename( " oldname " , " newname " ) rename a file/ directory
os.stat( ' path/filename ' ) get file/ directory information
os.sep outputs the operating system-specific path separator, " \\ " under win, " / " under Linux 
os.linesep outputs the line terminator used by the current platform, " \t\n " under win, under Linux as " \n "
os.pathsep outputs the string used to split the file path; under win, it is:
The os.name output string indicates the currently used platform. win -> ' nt ' ; Linux-> ' posix ' 
os.system( " bash command " ) Run the shell command and display it directly
os.popen( " bash command).read() Run the shell command and get the execution result 
os.environ Get the system environment variables

os.path
os.path.abspath(path) Returns the normalized absolute path of path os.path.split(path) Splits path into two-tuple of directory and filename Returns os.path.dirname(path) Returns the directory of path. In fact, the first element of os.path.split(path) os.path.basename(path) returns the last file name of path. If path ends with / or \, then it will return a null value.
                        i.e. the second element of os.path.split(path)
os.path.exists(path) Returns True if path exists; returns False if path does not exist
os.path.isabs(path) returns True if path is an absolute path
os.path.isfile(path) Returns True if path is an existing file. Otherwise return False
os.path.isdir(path) Returns True if path is an existing directory. Otherwise return False
os.path.join(path1[, path2[, ...]]) Returns after combining multiple paths, parameters before the first absolute path will be ignored
os.path.getatime(path) Returns the last access time of the file or directory pointed to by path
os.path.getmtime(path) Returns the last modification time of the file or directory pointed to by path
os.path.getsize(path) returns the size of path

Note: os.stat ('path/filename' ) gets the structure description of file/ directory information   

stat structure:

st_mode: inode protection mode
st_ino: inode node number.
st_dev: The device where the inode resides.
st_nlink: The number of links for the inode.
st_uid: User ID of the owner.
st_gid: Group ID of the owner.
st_size: The size in bytes of a normal file; contains data awaiting some special files.
st_atime: The time of the last visit.
st_mtime: The time of the last modification.st_ctime: " ctime " 
as reported by the operating system . On some systems (like Unix) the time of the last metadata change, on others (like Windows) the creation time (see the platform's documentation for details).

Common methods are as follows:

print(os.getcwd()) # Get the path where the current file is located

os.makedirs('dirname1/dirname2') # create multi-level
os.mkdir('dirname/son_dir') # create single level

print(os.listdir('D:\python11'))

print(os.name)

path = 'python%s2.mok.py'%os.sep
print(path)

os.system("dir") # exec
ret = os.popen("dir").read() # eval
print(ret)

 

2. Related methods of module and module import

1. What is a module

Common scenario: a module is a file containing python definitions and declarations, and the file name is the module name plus the suffix of .py.

   But in fact, the modules loaded by import are divided into four general categories: 

  1 Code written in python (.py file)

  2 C or C++ extensions that have been compiled as shared libraries or DLLs

  3 A package that wraps a set of modules

  4 Built-in modules written in C and linked to the python interpreter

2. Why use modules

   If you exit the python interpreter and then re-enter, the functions or variables you defined before will be lost, so we usually write the program to a file for permanent preservation, and execute it through python test.py when needed. test.py is called the script script.

    With the development of the program, there are more and more functions. In order to facilitate management, we usually divide the program into files one by one, so that the structure of the program is clearer and easier to manage. At this time, we can not only execute these files as scripts, but also import them into other modules as modules, realizing the reuse of functions.

3. How to use the module

1)import

import sys 
print(sys.modules) # When the python interpreter starts


# import a module,
# Equivalent to the module being executed from top to bottom
# The same module will not be imported multiple times

2) How to use import to import locally customized modules

When importing
a module, first create a memory space belonging to my_module,
load all the code
in the my_module module, and put the name method in the my_module module in the my_module namespace

my_module.funcl

my_module.func2()

print(my_module.money)

 

Alias ​​settings for import

import ....as...

example:

inp = input('json or pickle>>>')
if inp == 'json':
     import json as m
elif inp == 'pickle':
     import pickle as m

m.dumps({'k':'v'})
m.loads()

Summarize:

# import
# Import a module: The name of the module must conform to the variable definition specification
# Do not use a module with a built-in name you know
# The module will not be imported multiple times
# Importing a module is equivalent to
# opening up a new space
# Execution is imported The code in the module
# creates a module name as a reference to this space
# The names in the imported modules do not conflict with the names in the global file
# import. . . as . . .
# Import multiple modules import a,b,c

# PEP8 specification
# Each line of import should import a module
# If it is not a necessary requirement, all modules should be imported at the top of the file
# About the order of importing modules, import the built-in first, then import the extension, and finally import the custom

3)from ....import....

# When importing modules sys.modules import
# When using variables, look at the namespace globals()

 

Summarize:

# from ... import ...
# from module name import name
# The imported name belongs to the global directly, but points to the memory space where the name of the module is located
# If the imported name is a function or method, and references a global variable,
# still Use the variables in the module
# The imported name is the same as the global name, whoever preempts it last
# You can import multiple names, separated by commas
# You can also alias as
# from module import * Then the module will be imported by default. All names in the global
#* and __all__ are imported

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324845519&siteId=291194637