Definition of modules and packages os module

The os module is the module that interacts with the operating system. 
We have also used the os module before when changing the name of the file.

 

 

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
View Code
import os
 # The os module is a module that interacts with the operating system. 
# We have used the os module before, which is os.remove Delete the file os.rename () to change the name of the file 
# os.getcwd() # Get the current working directory is just python The directory path class of the script work is the linux access path linux is directly cwd 
# os.chdir('dirname') # Changing the working directory of the script is equivalent to cd ch under the shell is change dir 
# os.curdir() #Return to the current directory. Useless 
# os.curdir() # Returning the parent is .. also useless 
# os.makedirs('dirname1/dirname2') # To generate a multi-layer recursive directory is to create a multi-layer folder 
# os.removedirs('dirname1 /dirname2') #If the directory is empty, delete it and return to the previous level. If the previous level is also empty, delete it and so on. 
# os.mkdir('dirname') # Create an empty folder 
# os.rmdir ('dirname') # delete folder this folder must be empty 
# os.listdir('dirname') #Find all subdirectories in your directory including the hidden tree equivalent to linux
# os.remove() #Remove a file 
# os.rename('oldname','newname')#Rename 
# os.stat('path/filename') #Get file/directory information 
# os.sep #Output operation System specific path separator 
# print(os.getcwd())

Module: A module is a file containing python definitions and declarations. The file name is the module name plus the suffix of .py.

A module is to encapsulate a certain function in a py file and then it can be called

The meaning of the existence of modules: 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.

Importing a module When importing a module using import, it executes all the modules from top to bottom, and then calls it after the execution is complete.

Three things are done when the module my_module is imported for the first time:

  

1. Create a new namespace for the source file (my_module module). If the functions and methods defined in my_module use global, this namespace is accessed.

2. Execute the code contained in the module in the newly created namespace, see initial import import my_module

3. Create the name my_module to reference the namespace

That is, you first open up a space in your own file to store the modules you imported, and then when you import the modules, you will execute the code process in the newly created space in your own module, and then go to the your value to call what you need in the module

 

What is executed in the import module:

import my_moudule    #import the moudules module
a = 10
print (my_moudule.a) #Execute   the variable a in the imported module 
my_moudule.trashy() #Execute   the function in your module 
print (a)    #Execute your own variable

 

use of as

as is to change the name of your imported module to a name that you can easily remember.

import my_moudule as poor #Change   the usage name of your imported module to poor 
print (poor.a) #You   can directly use the changed name to use the contents of the imported module 
poor.trashy()
The following is a typical usage scenario of as. You can interpret the modules you import based on your input.
#This is the typical usage scenario of as. You can interpret the imported module according to your input inp 
= input( ' json or pickle>>> ' ).strip()
 if inp == ' json ' :
     import json as m
 elif inp == ' pickle ' :
     import pickle as m

m.pickle({'k':'v'})
m.loads()
        
Import multiple modules at once: 
import module 1, module 2, and module 3
can also import multiple modules at a time, but this is generally not recommended because it is not easy to operate when you do not want to unregister a module in the future

We can also choose to import a function in the module:

from imported modules import functions in modules

This import can only have the functions behind this import and cannot have all the functions in the imported module

eg:

from my_moudule import a
 print (a)
 print (my_moudule.a) #This    will report an error because you only imported a in the module instead of importing the entire module

So when importing, you need to look at the content behind your import

 

And directly take all the content in the module

from the module to import import *

This is to give all the information to the local and can be used directly

However, it is generally not recommended because I am afraid that some wrong information will also be brought into this document.

from  my_moudule  import *
print(a)
print(trashy())

 

For all imported *, there is an __all__ method, which is the most restrictive. We can limit the content of * by setting the information you want to be imported in the __all__ method when you import

from   my_moudule import * 
trashy()   #This can be 
trashy2() #This   error is because __all__==['a', 'trashy'] in the module you imported does not include trashy2

 

from ... import ... 
from module name import name
The imported name belongs to the global directly, but if the imported name points to the memory space where the module name is located,
if the imported name is a function or method, and references a global variable, the variable
in the module is still used
The imported name is the same as the global name, and whoever preempts it last
can import multiple names, separated by commas
and aliased as
from module import * By default, all names in the module will be imported to the global
* and __all__

 

 

 

Guess you like

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