Unit 3 Python Part1
Unit 3 Python Part1
complicated coding task into multiple, simpler, easier-to-manage sub-tasks. We call these
subtasks modules. Therefore, we can build a bigger program by assembling different
modules that act like building blocks.
MODULES IN PYTHON
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized.
A module is a file containing Python code, definitions of functions, statements, or classes.
An example_module.py file is a module we will create and whose name is example_module.
We employ modules to divide complicated programs into smaller, more understandable
pieces. Modules also allow for the reuse of code
Rather than duplicating their definitions into several applications, we may define our most
frequently used functions in a separate module and then import the complete module.
print(calc.add(10, 2))
# importing sys.path
print(sys.path)
Creating a Directory
There are different methods available in the OS module for creating a directory. These are –
os.mkdir(‘path’)
os.makedirs(‘path’)
Listing out Files and Directories with Python
There is os.listdir() method in Python is used to get the list of all files and directories in the
specified directory. If we don’t specify any directory, then the list of files and directories in
the current working directory will be returned.
Deleting Directory or Files using Python
OS module provides different methods for removing directories and files in Python. These
are –
Using os.remove(‘path’) (delete file path)
Using os.rmdir(‘path’) (delete folder)
print("Exit")
stdout
import sys
sys.stdout.write('Geeks')
stderr
try:
x = int("not_a_number")
except ValueError as e:
sys.stderr.write(f"Error: {str(e)}\n")
PYTHON JSON
Python JSON JavaScript Object Notation is a format for structuring data. It is mainly used
for storing and transferring data between the browser and the server. Python too supports
JSON with a built-in package called JSON. This package provides all the necessary tools for
working with JSON Objects including parsing, serializing, deserializing, and many more.
Convert from JSON to Python object
import json
# JSON string
employee = '{"id":"09", "name": "Nitin", "department":"Finance"}'
print("This is JSON", type(employee))
print("\nNow convert from JSON to Python")
# Convert string to Python dict
employee_dict = json.loads(employee)
print("Converted to Python", type(employee_dict))
print(employee_dict)