Python Tutorials
Python File Handling
Python Modules
Consider the module to match the code library.
A file containing a set of tasks that you want to include in your application.
To create a module simply save the code you want to a file with the .py
file extension:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
We can now use the newly created module, using the import
statement:
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: If you are using a module function, use the syntax: module_name.function_name.
The module can contain functions, as already described, but also variations of all types (arrays, dictionaries, objects, etc.):
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
You can compose a module file or whatever you like, but it should have a .py
file extension
You can create a noun when importing a module, using as
keyword:
Create an alias for mymodule
called mx
:
import mymodule as mx
a = mx.person1["age"]
print(a)
There are several modules built into Python, which you can download whenever you like.
Import and use the platform
module:
import platform
x = platform.system()
print(x)
There is a built-in function to list all the job names (or variable names) in the module. dir()
function:
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir () function can be applied to all modules, including the ones you created.
You can choose to import only module components, using the keyword from
.
The module named mymodule
has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1
= {
"name": "John",
"age": 36,
"country":
"Norway"
}
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Note: If you enter using a from
keyword, do not use the module name when referring to module items. Example: person1 ["years"]
, not mymodule.person1 ["years"]