More , Please visit mine Personal blog .
A module is a file that contains all defined functions and variables , Its suffix is .py
. Modules can be introduced by other programs , To call functions in the module . This is also used python Standard library method .
Want to reference a module , Just execute import The sentence is enough . Let's look at an example .
# Filename: printHello.py
def hello( name ):
print ("Hello : ", name)
Create a new one printHello.py
The file of , Write a hello
Function of . This file is a module .
# Filename: test.py
# The import module
import printHello
# Now you can call the functions contained in the module
printHello.hello("Python")
We will in Same directory So let's make a new one test.py
The file of , Use import
Import printHello
This module . Be careful : When importing a module , No suffix .py
. It can be used at this time printHello.hello
This form invokes... In the module hello
Function .
$ python3 test.py
Hello : Python
Direct operation test This script , We can see , Results output Hello Python.
here , We have completed the module call .
Python Of from … import
Statement can import a specified part from the module into the current script .
For example, the example just now :
# Filename: test.py
# The import module
from printHello import hello
# Now you can call the functions contained in the module
hello("Python")
We switch to from … import
sentence , Namely from This module import function , This eliminates the need to import the entire module , But only import the functions we need . The function name is also written directly when calling , Instead of writing the module name .
Package is a kind of management Python The form of the module namespace . To understand it in popular terms , Is the name of the folder .
Again, the previous example , Do you remember? ? These two files must be in the same directory , How to import modules in different directories ? And that's where it comes in “ package ” The concept of .
# Filename: package/printHello.py
def hello( name ):
print ("Hello : ", name)
For example, we will printHello.py This file is placed in package Under this folder .
# Filename: test.py
# The import module
from package.printHello import hello
# Now you can call the functions contained in the module
hello("Python")
that , When we import the module, we can use .
Indicates a folder split . Other , Just like the previous usage .
Upper Baidu , Google it . Understand the usage and meaning of functions in the following modules .
import sys
sys.path[0]
sys.argv[0]
import os
os.getcwd()
os.path.dirname(path)
os.sep
os.rename('test.txt', 'test.py’)
os.remove('test.txt’)
os.path.isfile('test.txt’)
os.path.exists(directory)
Official account : Pangao will accompany you to learn programming , reply 019, Get the answer to the exercise .