Python - Lecture 2
Python - Lecture 2
Modules can be created simply by saving Python code in a .py file and then imported
using the import statement.
Its goal: group related pieces of functionality, which can then be imported and used
elsewhere, keeping your code clean and organized.
Module
Intro s
module1.py
project.py
module2.py
module3.py
import module_name
module1.py
project.py
import module1
module2.py
module3.py
To
2. You can import specific functions or variables from a module using:
Here, python imports only the specified block_name from the module, rather
than importing the entire module.
Files
open(file_name, mode)
Files
fl = open(“D:/some_file.txt”, ‘r’)
#reads the entire content of the file some_file.txt
fl.read()
Some text on line
#output: Some text on line 1.
1. Other text on
Other text on line 2.
line 2.
fl.read(4)
#output: Some
fl.readline()
#output:text on line 1.
Files
#Read all lines into a
fl =
open(“D:/some_file.
txt”, ‘r’)
for line in f1:
print(line)
Files
some_file.txt
Files
some_file.txt
Some
This istext
newon line
content
1.
fl = open(“some_file.txt”,
Other text on line
‘w’) fl.write(“This is new 2.
content”)
Files
some_file.txt
Some new
This istext
old on line
content
1.
fl = open(“some_file.txt”,
Other text on line
‘w’) fl.write(“This is new 2.
content”) fl.seek(8)
fl.write(“old”)
Files
some_file.txt
This istext
Some new
old on line
content
1.
fl = open(“some_file.txt”, content is
Other text on line
‘w’) fl.write(“This is new appended
2.
content”) fl.seek(8)
fl.write(“old”)
fl.close()
fl =
open(“some_fil
e.txt”, ‘a’)
fl.write(“\n
content is
appended”)
Open Source Department –
Python Standard
Library
Python Standard
math Library
import math
math.pi # 3.14
p
pip is a package management system used to install and manage
software packages written in Python
-It ensures that files are properly closed after their use, even if
an error occurs during file processing.
fp.read()
Comprehension
It is an easy method to construct
a list
Outpu Input
t sequence