You are on page 1of 36

Network Protocols Network Protocols

Practice site for FTP Point-to-Point Protocol (PPP) is an open standard protocol that is mostly used
Demo for Web-based Administration:
Location: http://demo.wftpserver.com:5466/ to provide connections over point-to-point serial links. The main purpose of PPP is to transport
Username: demo-admin Layer 3 packets over a Data Link layer point-to-point link. PPP can be configured on:
Password: demo-admin Asynchronous serial connection like Plain old telephone service (POTS) dial-up
Synchronous serial connection like Integrated Services for Digital Network (ISDN) or point-to-
Demo for Web-based Client: point leased lines.
Location: http://demo.wftpserver.com/ Practice it PPP consists of two sub-protocols:Link Control Protocol (LCP): set up and negotiate control
Username: demo-user options on the Data Link Layer (OSI Layer 2). After finishing setting up the link, it uses NCP.
Password: demo-user Network control Protocol (NCP): negotiate optional configuration parameters and facilitate for
the Network Layer (OSI Layer 3).
Login using your own client with FTP, FTPS, SFTP protocol: Before a PPP connection is established, the link must go through three phases of session
Location: demo.wftpserver.com establishment:
Username: demo-user 1. Link establishment phase: In this phase, each PPP device sends LCP packets to configure and
Password: demo-user test the data link
FTP Port: 21 2. Authentication phase (optional): If authentication is enabled, either PAP or CHAP will be
password challenge handshake
FTPS Port: 990 used. PAP and CHAP are two authentication protocols used in PPP authentication

SFTP Port: 2222 3. Network layer protocol phase: PPP sends NCP packets to choose and configure Network
Layer protocol (OSI Layer 3) to be encapsulated and sent over the PPP data link
Courtesy - https://www.wftpserver.com/onlinedemo.htm
Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

165
Network Protocols Network Protocols

HTTP - HTTP stands for hypertext transfer protocol and is used to transfer data across Remote login – A remote login facility permits a user who is using one computer to login to
the Web. It allow users of the World Wide Web to exchange information found on web remote computer or interact with a program on another computer. Command given at
pages. When accessing any web page entering http:// in front of the address tells the remote location is processed by server and result displayed over remote location.
browser to communicate over HTTP.
How It Works-
It is a connectionless text based protocol. Clients (web browsers) send requests through
request object of http to web servers for web pages / images etc.Web server respond
accordingly through response object of http After this cycle(request – response), the
connection between client and server across the Internet is disconnected. A new connection
must be made for each request(means for each web page).
Telnet – Telnet is most popular protocol for accessing remote site/server. Using telnet client
This diagram shows the software on our computer, we can make a connection to a telnet server (that is, the remote
working of http protocol. host). Once our telnet client establishes a connection to the remote host, our client becomes
Working with dns server a virtual terminal, allowing us to communicate with the remote host from our computer. In
and working with web most cases, we need to log into the remote host, which requires that we have an account on
Server both. that system. Occasionally, we can log in as guest or public without having an
account.Generally it is used in unix based client server system to interact.

Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

166
Network Protocols Network Protocols

Wireless/Mobile Communication Protocol- GSM- Global System for Mobile Communications, is a standard
Wireless communications is a type of data communication developed by the European Telecommunications Standards Institute
that is performed and delivered wirelessly between mobile (ETSI) for 2G cellular networks for mobile phones.
It initially started as a circuit switching network, but later packet
devices.
switching was implemented after integration General Packet Radio
The network architecture used is unique in that it Service (GPRS) technology as well. The widely-used GSM frequency
separates the mobile network(s) from fixed networks and bands are 900 MHz and 1800 MHz.
provides connectivity between the two via the protocols GSM mobile use sim cards -Subscriber Identity Module card is a tiny,
specially used for wireless/mobile communication which portable memory chip that stores information about you as a cell
are not as wireless/mobile communication protocol.E.g. of phone user. On it, there’s a seventeen-digit code that designates its
country code of origin, the system carrier and a unique user ID.
such protocols are GSM,GPRS and WLL.

Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

167
Network Protocols Network Protocols

How GSM works-


A Mobile Station: It is the mobile phone
which consists of the transceiver, the GPRS-General Packet Radio
display and the processor and is Service,In GSM cell phone systems,
controlled by a SIM card operating over there will always be idle radio capacity.
the network. Which is not being used and it stays
Base Station Subsystem: It connects
unused until other cell phone users
mobile station and network subsystem.
decide to make phone calls. GPRS uses
It consists of the Base Transceiver Station which contains the radio transceivers and handles
this idle radio capacity to establish a
the protocols for communication with mobiles. It also consists of the Base Station Controller
which controls the Base Transceiver station and acts as a interface between the mobile station
data network to be used for data
and mobile switching centre. transmission(115 kbps).
Network Subsystem: It provides the basic network connection to the mobile stations. The Gateway GPRS Support Node (GGSN) & Serving GPRS Support Node (SGSN) are two
basic part of the Network Subsystem is the Mobile Service Switching Centre which provides major components of gprs network .
access to different networks like ISDN, PSTN etc. It also consists of the Home Location Register The GGSN converts incoming data traffic from mobile users (via the SGSN) and
and the Visitor Location Register which provides the call routing and roaming capabilities of forwards it to the relevant network, and vice versa. The Serving GPRS Support
GSM. It also contains the Equipment Identity Register which maintains an account of all the Node (SGSN) to keep mobile users connected to the Internet and IP-based
mobile equipments wherein each mobile is identified by its own IMEI number. IMEI stands for
applications.
International Mobile Equipment Identity.
Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

168
Network Protocols Mobile communication
technologies

WLL: Wireless Local Loop


Initially, the telephones were connected
via copper cables but with wll protocol
telephones with wll support can be used
while roaming.
When somebody calls from WLL to
another person, the Base Trans-Receiver
accepts the signal and sends it to Base-
Station Controller.
Controller decodes them according to given code and sends it to Base Station
Manager which sends it to Telephone Exchange. This gets back to a specific
customer on the same route via different Trans-Receiver.
However, this was quite inefficient when it has to cover a bigger ground, probably
that’s why it became obsolete.

Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

169
Mobile communication Email Protocols
technologies
Mobile processors, also known as chipset, is a component that controls Email –Electronic mail is a facility that allows users to transmit messages across the
everything going on in your smartphone and ensures it functions correctly.
internet in fast and secure manner.
processors based on specs – Cores and clock speed
A processor performance mostly depends on two specifications; the number of cores and
the clock speeds .A core is an element of the processor that implements and executes
tasks. Smartphones today, come with multiple cores. Each core is designed to handle and
execute tasks. More the number of cores, more and heavier apps it can e.g. dual-core
(two), quad-core (four) and octa-core (eight), hexa-core (six).etc.
Popular Entry-Level SoCs
• Snapdragon 665-The most popular affordable chipset that replaced Snapdragon 400 series.
• MediaTek Helio P70 has emerged as a popular alternative to Snapdragon chipsets.
Popular Mid-Range SoCs Email created using email client program->on press of send button ,it is delivered to
• Snapdragon 765/ 765G is the first Qualcomm chipset with an integrated 5G modem. sender’s mail server through SMTP(Simple mail transfer protocol)->which further
• MediaTek G90/ G90T-only popular MediaTek chipset in 2019. transmit the same through internet to recipient’s mail server->whenever recipient’s
Popular High-End SoCs email client program’s inbox is opened,that email is delivered to inbox through
• Snapdragon 865 -The latest Qualcomm flagship that will be a part all 2020 flagships. POP3 (post office protocols 3rd version)->which user will read in email client
• Kirin 990 5G/ 990-This is the current Huawei flagship chipset in Mate 30 and P40- phones.
program.
Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

170
Email Protocols Email Protocols

SMTP – Most of the internet systems use SMTP as a method to transfer mail from one user to another. POP3 – Post Office Protocol version 3 (POP3) is a standard
SMTP is a push protocol and is used to send the mail to email server. it is usually used with one of two
other protocols, POP3 or IMAP, that let the user save messages in a server mailbox and download them mail protocol used to receive emails from a remote server
periodically from the server.An alternative to SMTP that is widely used in Europe is X.400. Many mail
servers now support Extended Simple Mail Transfer Protocol (ESMTP), which allows multimedia files to
to a local email client. POP3 allows us to download email
be delivered as e-mail. messages on our local computer and read them even when
we are offline. Note, that when we use POP3 to connect to
our email account, messages are downloaded locally and
removed from the email server. This means that if we
access our account from multiple locations, that may not be
the best option for us. On the other hand, if we use POP3,
The SMTP model is of two type :
• End-to- end method our messages are stored on our local computer, which
• Store-and- forward method reduces the space of email account uses on your web
The end to end model is used to communicate between different organizations whereas the store and
forward method is used within an organization. server.
Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

171
Protocols for chat Protocols for chat
& video conferencing & video conferencing
VOIP – Voice over Internet Protocol (VoIP), is a technology that allows us to make voice
calls using a broadband Internet connection instead of a regular (or analog) phone line. Services provided by VOIP – Phone to phone,pc to phone ,phone to pc,voice
VoIP services convert our voice into a digital signal that travels over the Internet. If we are to email,ip phone,toll free number,call center applications,vpn,unified messaging etc.
calling a regular phone number, the signal is converted to a regular telephone signal before it
reaches the destination. VoIP can allow us to make a call directly from a computer, a special Protocols used for VOIP are
VoIP phone. In addition, wireless "hot spots" in locations such as airports, parks, and cafes • Session Initiation Protocol (SIP)- connection management protocol developed by the IETF
allow us to connect to the Internet and may enable us to use VoIP service wirelessly. • H.323 - one of the first VoIP call signaling and control protocols that found widespread
Advantages: implementation.
• Less Cost • Real-time Transport Protocol (RTP)- transport protocol for real-time audio and video data
• Accessibility • Real-time Transport Control Protocol (RTCP)- sister protocol for RTP providing stream
• Flexibility statistics and status information
• Voice Quality • Secure Real-time Transport Protocol (SRTP) - encrypted version of RTP
• Extra/Less Expensive Features • Session Description Protocol (SDP) - file format used principally by SIP to describe VoIP
Disadvantages: connections
• Reliable Internet Connection Required
• Power Outages/Emergencies
• Latency

Visit : python.mykvs.in for regular updates Visit : python.mykvs.in for regular updates

172
Wireless technology
BASIS OF
WI-FI WiMAX Why do we need a programming language?
COMPRISON
Wi-Fi is an acronym for Wireless Fidelity. WiMAX is an acronym for Worldwide Interoperability • To communicate with the computer
Description
It is a wireless networking technology for Microwave Access. It also goes by the IEEE name
that uses radio waves to provide wireless 802.16. It is a technology standard for long-range
• Computers understand binary (machine) language
high-speed internet and network wireless networking for both mobile and fixed consisting of only 2 symbols 0 and 1
Protocol
connections.
Uses CSMA/CA protocol
connection.
Uses connection based MAC protocol.
• Users understand Natural language
Licensed and
Unlicensed Exclusively unlicensed Can run on both licensed and unlicensed spectrum. Machine
Natural Language
Spectrum Language (binary)
Data (English) Which
Transmission data at speeds up to 54 mbps. data at speeds upto 40mbps. Language ?
Rates
Channel
fixed channel bandwidth of 20 MHz. flexible channel bandwidth - 1.25 MHz to 20 MHz.
Bandwidth
Defined under IEEE 802.11x standards Standardized under 802.16y family of wireless
IEEE Standards
where x is various Wi-Fi versions. networking where y refers to various WiMAX versions.
8/17/2022 Demo Session 3
coverage of up to 100 meters for Non-line of sight connectivity covers a radius of above
Coverage outdoor applications and 30 meters for 25 kilometers (Km). For line of sight connectivity
indoor coverage. coverage area of above 600- square

Visit : python.mykvs.in for regular updates

173
Why not English? Why not binary language?
• English is ambiguous • Too difficult to learn
• I am Ramana vs I am rich • Remembering 256 ASCII code sequences
• English is inconsistent • Too lengthy
• Same word (e.g. well) has different meanings at different times • For every letter 8 bits have to be used
• English is context sensitive
• The meaning of a word or expression changes with context
• English is relative
• Come here etc.

8/17/2022 Demo Session 4 8/17/2022 Demo Session 5

174
Solution – Programming language Problem solving
• We use the programming language to write a program, which
executes on the computer to solve a problem.
• The problems can be of various types:
• Mathematical
• Scientific
• Real world
• All problems follow a simple pattern:
• Input Process Output

8/17/2022 Demo Session 6 8/17/2022 Demo Session 7

175
Problem solving - Examples Problem solving - Mapping
• Identify the input, process and output for the
Real world

following problems: INPUT PROCESS OUTPUT


• Making Aloo Paratha
• Calculating the Average of a class (of n students)
• Printing the memorandum of marks for a student
• Checking whether a given number is even or not Operators
Data types Data types
Statements
Computer

8/17/2022 Demo Session 8 8/17/2022 Demo Session 9

176
Introduction What is Python?
 Python provides basic and advanced concepts of Python.
 Python is a general purpose, dynamic, high-level, and interpreted programming language.
 Python is a simple, general purpose, high level, and object-oriented
 programming language.  It supports Object Oriented programming approach to develop applications.

 Python is an interpreted scripting language.  It is simple and easy to learn and provides lots of high-level data structures.
 Guido Van Rossum is known as the founder of Python programming.
 Python is easy to learn yet powerful and versatile scripting language, which makes it

Why Name Python ? attractive for Application Development.

Guido van Rossum was also reading the published scripts from “Monty Python's Flying  Python's syntax and dynamic typing with its interpreted nature make it an ideal language for

Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that scripting and rapid application development.
was short, unique, and slightly mysterious, so he decided to call the language Python.

177
Python Features Python Applications
Python provides many useful features which make it popular and valuable from the other
programming languages. Python is known for its general-purpose nature that makes it applicable in almost every
domain of software development.
1) Easy to Learn and Use 9) GUI Programming Support
2) Expressive Language 10) Integrated
1) Web Applications 6) Business Applications
3) Interpreted Language 11) Embeddable
2) Desktop GUI Applications 7) Audio or Video-based Applications
4) Cross-platform Language 12) Dynamic Memory Allocation
3) Console-based Application 8) 3D CAD Applications
5) Free and Open Source

6) Object-Oriented Language 4) Software Development 9) Enterprise Applications

7) Extensible 5) Scientific and Numeric 10) Image Processing Application

8) Large Standard Library

178
PYTHON
Working Environment

179
180
Now click on the start button and type idlE( python 3.8) the following window will open

REPL( READ EVULATE PRINT LOOP)

The above window is called PYTHON SHELL( INTERATIVE MODE)

Now click on the file & select new file that is known as PYTHON INTERPRETER
(SCRIPT MODE)

181
INTERACTIVE MODE WHAT IS A PROGRAM?
 Interactive mode, also known as the REPL provides us with a quick way of running blocks or a single line of Python A program is a sequence of instructions that specifies how to perform a computation.
code.
The computation might be something mathematical, such as solving a system of equations or finding the roots
 The code executes via the Python shell, which comes with Python installation.
 The interactive mode involves running your codes directly on the Python shell which can be accessed from the
of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document

terminal of the operating system. or something graphical, like processing an image or playing a video.

A FEW BASIC INSTRUCTIONS APPEAR IN EVERY PROGRAMMING LANGUAGE:


SCRIPT MODE

 In the script mode, you have to create a file, give it a name with a .py the extension then runs your code. The INPUT: Get data from the keyboard, a file, the network, or some other device.
interactive mode is suitable when running a few lines of code. The script mode is recommended when you need to OUTPUT: Display data on the screen, save it in a file, send it over the network, etc.
create large applications. MATH: Perform basic mathematical operations like addition and multiplication.
 In script mode, a file must be created and saved before executing the code to get results. In interactive mode, the CONDITIONAL EXECUTION: Check for certain conditions and run the appropriate code.
result is returned immediately after pressing the enter key. REPETITION: Perform some action repeatedly, usually with some variation.
 In script mode, you are provided with a direct way of editing your code. This is not possible in interactive mode.

182
WHAT IS INPUT?
Input is reading the data from the keyboard or any input devices, then we can call it
as input.
WHAT IS OUTPUT?
Output is a displaying the data on the monitor or any output device, then we can call
What is Character Set?
it as output.
Character set is a bunch of
OUTPUT:
identifying elements in the
 New print format is introduced in Python 3.x version programming language.
 “print” function can be used for displaying the data on monitor or console
 The difference between version 2.x and version 3.x is, parenthesis is not used in
version 2.x, but parenthesis is used in version 3.x

8/17/2022 Demo Session 23

183
PYTHON CHARACTERSET TOKENS OR LEXICAL UNIT

PYTHON What is Token?


CHARACTER
SET
Individual elements that are
identified by programming language are
• Letters:- A-Z, a-z called tokens or lexical unit.
• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab,
Carriage Return.
• Other Characters:- Python can process all 256 ASCII and
Unicode Characters.

184
TOKENS / LEXICAL UNITS
1. Key
Words

PYTHON
5.
Punctuators
2.
Identifiers COMMENTS
TOKENS

4.
Operators.
3. Literals

185
COMMENTS
Python Programming language supports two types of comments.
1. SINGLE LINE COMMENTS.
2. MULTIPLE LINE COMMENTS.

1. SINGLE LINE COMMENTS.


Single line comments start with ‘#’ Symbol.
PYTHON
EXAMPLE:
#this is single line comment
KEYWORDS
2. MULTIPLE LINE COMMENTS.
Multiple line comments start with triple quote and end with triple quote.
EXAMPLE:
‘’’ Hi this is multi line
Comments, please use for document
It is good ‘’’

186
KEYWORDS
 Python Keywords are special reserved words that convey a special meaning to the compiler/interpreter. 3. LITERALS / CONSTANT VALUES
 Each keyword has a special meaning and a specific operation. These keywords can't be used as a variable.
 They are 33 keywords in python
What is literals?
True False None and as

asset def class continue break Literals are also called as constants
or constant values these are the values
else finally elif del except
which never change during the
global for if from import execution of program.
raise try or return pass

nonlocal in not is lambda

while with yield

187
TYPES OF LITERALS / CONSTANT VALUES 1. STRING LITERALS OR CONSTANTS

What are the types of literals? What is string?


Sequence of letters enclosed in
1) String Literals or Constants. quotes is called string or string literal or
constant.
2) Numeric Literals or Constants.
Python supports both form of
3) Boolean Literals or Constants. quotes i.e.
4) Special Literal None. ‘Hello’
5) Literal Collections. “Hello”

188
REPRESENTATION OF STRING REPRESENTATION OF STRING
>>> s = “Hello Python”
This is how Python would index the string:
Backward Indexing
To access the first character on the
string you just created, type and enter
the variable name s and the index 0
within square brackets like this:
>>>s[0]
You’ll get this output:
Forward Indexing ‘H’

189
REPRESENTATION OF STRING REPRESENTATION OF STRING

The expression introduces you to the len


To access the last character, you can use
function. There is actually an easier way
this expression:
Len() function
to
>>>s[len(s)-1]
is used to find access the last item on the string:
the length of >>>s[-1]
You’ll get the output:
the string. ‘n’
‘n’
To access the penultimate character:
>>>s[-2]
‘o’

190
TYPES OF STRINGS SINGLE LINE STRINGS

What are the types of strings supported


in python? Strings created using single quote or
double quote must end in one line are
Python supports two ways of called single line strings
representation of strings: For Example:
Item=“Computer”
1) Single Line Strings. Or
2) Multi Line Strings. Item= ‘Computer’

191
MULTI LINE STRINGS

Strings created using single quote or PYTHON


double quote and spread across multiple
lines are called Multi Line Strings. VARIABLES
by adding backslash \ one can
continue to type on next line.
For instance: Item = ‘Key\
board’

192
PYTHON VARIABLES EX
Identifier Naming
 VARIABLES
Definition:  Variables are the example of identifiers.  CLASSES

 Variable is a name that is used to refer to memory location.  OBJECT


 An Identifier is used to identify the literals used in the program.
 MODULES
 Python variable is also known as an identifier and used to hold value. The rules to name an identifier are.  FUNCTIONS
 CONSTANTS
 In Python, we don't need to specify the type of variable because Python is a infer language and  The first character of the variable must be an alphabet or underscore ( _ ).

smart enough to get variable type.  All the characters except the first character may be an alphabet of lower-case (a-z), upper-case

 Variable names can be a group of both the letters and digits, but they have to begin with a letter or (A-Z), underscore, or digit (0-9).

an underscore.  Identifier name must not contain any white-space, or special character (! @, #, %, ^, &, *).

 It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two  Identifier name must not be similar to any keyword defined in the language.

different variables.  Identifier names are case sensitive; for example, my name, and MyName is not the same.
 Examples of valid identifiers: a123, _n, n_9, etc.
 Examples of invalid identifiers: 1a, n%4, n 9, etc.

193
 In Python, variables are a symbolic name that is a reference or pointer to an object.
 The variable b refers to the same object that a points to because Python does not create another
 The variables are used to denote objects by that name.
object.
OBJECT  Let's assign the new value to b. Now both variables will refer to the different objects.
 An object is simply a collection of data (variables) and methods (functions) that act on those
a = 50
data. Similarly, a class is a blueprint for that object. ...
b =100
 An object is also called an instance of a class and the process of creating this object is
called instantiation.
OBJECT IDENTITY
a = 50
The variable a refers to an integer object.  In Python, every created object identifies uniquely in Python.
Suppose we assign the integer value 50 to a new variable b.  Python provides the guaranteed that no two objects will have the same identifier.
a = 50
 The built-in id() function, is used to identify the object identifier.
b=a
Python manages memory efficiently if we assign the same variable to two different values.

194
EXAMPLE  We assigned the b = a, a and b both point to the same object.
Valid Variables Name.
a = 50
name = "A"  we have declared a few valid variable names such as name, _name_ ,
b=a  When we checked by the id() function it returned the same number.
print(id(a)) Name = "B" etc.
print(id(b))  We reassign a to 500; then it referred to the new object identifier.
# Reassigned variable a naMe = "C"  But it is not recommended because when we try to read code, it may
a = 500
print(id(a)) NAME = "D" create confusion.
Valid Variables Names Example. n_a_m_e = "E"  The variable name should be descriptive to make code more readable.
OUTPUT
140713757808992 name = "Krishna"
_name = "F"
140713757808992 age = 20
843812079024 name_ = "G"
marks = 80.50 Output: Output:
print(name) Krishna _name_ = "H"
ABCDE DE FGF I
print(age) 20 na56me = "I"
print(marks) 80.5 print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)

195
THE MULTI-WORD KEYWORDS CAN BE CREATED BY THE FOLLOWING METHOD. Multiple Assignment
Camel Case  Python allows us to assign a value to multiple variables in a single statement, which is also
 In the camel case, each word or abbreviation in the middle of begins with a capital letter. known as multiple assignments.

 There is no intervention of whitespace. We can apply multiple assignments in two ways, either by

For example - nameOfStudent, valueOfVaraible, etc. assigning a single value to multiple variables
or
Pascal Case
assigning multiple values to multiple variables.
It is the same as the Camel Case, but here the first word is also capital. 1. Assigning single value to multiple variables
Eg:
For example - NameOfStudent, etc.
x=y=z=50 Output:
Snake Case 50
print(x)
In the snake case, Words are separated by the underscore. 50
print(y)
50
For example - name_of_student, etc. print(z)

196
2. Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15

Print(a)

print (b)

print (c )

Output: 5 10 15

The values will be assigned in the order in which variables appear.

By using semicolon also we can declare the multiple


variables
a = 5 ; b = 6; c = a+b
print( c ) 8/17/2022 Demo Session 51

197
1. Creating a new file and writing text to it: 9. Checking if a file exists:

import os
with open('new_file.txt', 'w') as f:
if os.path.isfile('file.txt'):
f.write('Hello, world!')
print('File exists.')
2. Reading the contents of a file and printing them to the console:
with open('file.txt', 'r') as f: else:

contents = f.read() print('File does not exist.')

print(contents) 10. Getting the size of a file in bytes:


import os
3. Reading the contents of a file line by line and printing them to the console:
size = os.path.getsize('file.txt')
with open('file.txt', 'r') as f:
print(f'The size of the file is {size} bytes.')
for line in f:

print(line) 11. Checking if a file is readable:


4. Appending text to an existing file:
import os

with open('file.txt', 'a') as f: if os.access('file.txt', os.R_OK):

f.write('This text will be appended to the file.') print('File is readable.')

5. Writing a list of strings to a file, one string per line: else:

print('File is not readable.')


lines = ['line 1', 'line 2', 'line 3']
12. Checking if a file is writable:
with open('file.txt', 'w') as f:
import os
f.writelines('\n'.join(lines))
if os.access('file.txt', os.W_OK):
6. Reading a CSV file and printing its contents: print('File is writable.')

import csv else:

with open('data.csv', 'r') as f: print('File is not writable.')

reader = csv.reader(f) 13. Checking if a file is executable:


import os
for row in reader:
if os.access('file.txt', os.X_OK):
print(row)
print('File is executable.')
7. Writing a CSV file:
else:
import csv print('File is not executable.')
data = [['Name', 'Age'], ['Alice', '25'], ['Bob', '30'], ['Charlie', '35']]
14. Renaming a file:
with open('output.csv', 'w', newline='') as f: import os

writer = csv.writer(f) os.rename('old_file.txt', 'new_file.txt')

writer.writerows(data) 15. Deleting a file:


import os
8. Copying the contents of one file to another:
os.remove('file.txt')
with open('input.txt', 'r') as f1, open('output.txt', 'w') as f2:

f2.write(f1.read())

198
16. Creating a new directory: 22. Remove all whitespace from a file:

import os with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:

os.mkdir('new_directory') for line in input_file:

17. Deleting an empty directory: line = line.replace(' ', '')

output_file.write(line)
import os
23. Find and replace text in a file:
os.rmdir('empty_directory')

18. Checking if a directory exists: with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:

for line in input_file:


import os
line = line.replace('apple', 'orange')
if os.path.isdir('directory'):
output_file.write(line)
print('Directory exists.')
24. Sort the lines of a file:
else:

print('Directory does not exist.') with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:

19. Count the number of lines in a file: lines = input_file.readlines()

lines.sort()
with open('example.txt', 'r') as file:
for line in lines:
line_count = 0
output_file.write(line)
for line in file:
25. Reverse the lines of a file:
line_count += 1

print(f'The file contains {line_count} lines.') with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:

20. Count the number of words in a file: lines = input_file.readlines()

lines.reverse()
with open('example.txt', 'r') as file:
for line in lines:
word_count = 0
output_file.write(line)
for line in file:
26. Encrypt the contents of a file using a Caesar cipher:
words = line.split()

word_count += len(words) def caesar_cipher(text, shift):

print(f'The file contains {word_count} words.') encrypted = ''

21. Count the number of characters in a file: for char in text:

if char.isalpha():
with open('example.txt', 'r') as file:
if char.islower():
char_count = 0
encrypted += chr((ord(char) + shift - 97) % 26 + 97)
for line in file:
else:
chars = list(line)
encrypted += chr((ord(char) + shift - 65) % 26 + 65)
char_count += len(chars)
else:
print(f'The file contains {char_count} characters.')

199
#27. Program to write contents into details.txt myfile2.close()
f=open("details.txt","w") print("Copied successfully.....")
f.write("This is rahul ranavir\n") #31. Getting the name of current working directory
f.write("Hi, This is book\n") import os
f.close() pwd=os.getcwd()
#28. Program to find the word "This" in the details.txt and display line no in which the given print("Current Directory:",pwd)
word is found
#32. Create a file, add the content, copy to another file and append new content in second file.
f=open("details.txt","r")
f1=open("file1.txt","w")
word="This"
f1.write("This is my file contents")
c=0
f1=open("file1.txt","r")
for i in f.readlines():
f2=open("file2.txt","w")
c+=1
x=f1.read()
if word in i.split():
f2.write(x)
print("Found at " +str(c))
f1.close()
f.close()
f2.close()
#29. writing string as a record to file
f3=open("file2.txt","a")
myfile=open("book.txt","w")
f3.write("Hello")
ans='yes'
f3.close()
while ans=='yes':
#33. Program to count total no of lines present in the given file
bno=int(input("Enter book number:"))
filename=input("Enter name of the file")
bname=input("Enter book name:")
file=open(filename)
author=input("Enter author name:")
print("total no of lines in",filename,"are",str(len(file.readlines())))
price=int(input("Enter book price"))
34. Filtering files in a directory by extension
brec=str(bno)+","+bname+","+author+","+str(price)+"\n"
import os
myfile.write(brec)
files = os.listdir(".")
ans=input("Add more ?")
for file in files:
myfile.close()
if file.endswith(".txt"):
#30. To copy the content of one file to another file
print(file)
myfile1=open("book.txt","r")
35. Checking if a directory exists
myfile2=open("book_backup.txt","w")
str1=" " import os

while str1: if os.path.isdir("mydir"):

str1=myfile1.readline() print("Directory exists")

myfile2.write(str1) else:

myfile1.close() print("Directory does not exist")

200

You might also like