0% found this document useful (0 votes)
81 views34 pages

Module 3 Notes

This document serves as an introduction to Python programming, focusing on string manipulation, file handling, and various string methods. It covers string types, escape characters, indexing, slicing, and the use of operators with strings, along with practical examples and projects. Additionally, it highlights the importance of using f-strings for readability and provides an overview of useful string methods for text processing.

Uploaded by

palamakularamesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views34 pages

Module 3 Notes

This document serves as an introduction to Python programming, focusing on string manipulation, file handling, and various string methods. It covers string types, escape characters, indexing, slicing, and the use of operators with strings, along with practical examples and projects. Additionally, it highlights the importance of using f-strings for readability and provides an overview of useful string methods for text processing.

Uploaded by

palamakularamesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

MODULE 3
INTRODUCTION TO PYTHON PROGRAMMING

Syllabus: Manipulating Strings: Working with Strings, Useful String Methods, Project: Password Locker,
Project: Adding Bullets to Wiki Markup Reading and Writing Files: Files and File Paths, The os.path
Module, The File Reading/Writing Process, Saving Variables with the shelve Module,Saving Variables
with the print.format() Function, Project: Generating Random Quiz Files, Project: Multi Clipboard,
Textbook 1: Chapters 6 , 8

E
DEFINITION: In programming, a string is a sequence of characters enclosed in quotation marks. These

C
characters can be letters, numbers, symbols, or whitespace.

N
JN
Types of Strings:

1.​ Single-quoted strings:


○​ Created using single quotes (' ')

L,
○​ Example: 'Hello'

IM
2.​ Double-quoted strings:
○​ Created using double quotes (" ")
○​ Example: "World"
,A
3.​ Raw strings:
○​ Created by prefixing the string with r or R (e.g., r'...' or R'...').
M

○​ These strings treat backslashes as literal characters and not escape characters.
○​ Example: r'C:\Users\Al'
EE

4.​ Multiline strings:


○​ Created using triple quotes (''' or """).
AS

○​ Used for strings that span multiple lines.

Example:​
W

'''This is a
multiline string.'''
YA

String Example:
LI

name = "Alice" # This is a string


AA

Strings are widely used for text processing, storing data, and more in programming.

1. WORKING WITH STRINGS

Python provides several ways to create, manipulate, and display strings. Let’s break it down step by step:

String Literals:A string in Python is a sequence of characters enclosed in quotes. There are two types of
string quotes:

Aaliya Waseem,Dept.AIML,JNNCE
1
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

1.​ Single Quotes: 'This is a string'


2.​ Double Quotes: "This is a string"

Using Double Quotes for Strings: If you want to include a single quote inside a string, you can use
double quotes:
spam = "That's Alice's cat."

In this case, the double quotes tell Python where the string starts and ends, and the single quote inside the
string is not considered as the end of the string.

E
C
Escape Characters: Sometimes, you need special characters inside a string, such as quotes, backslashes,
or new lines. This is where escape characters come in.

N
JN
What is an Escape Character?

An escape character is a backslash (\) followed by a character that modifies the string. Even though it
consists of two characters, it is considered a single escape character.

L,
IM
,A
M
EE
AS
W

Example of Escape Characters

Single Quote Inside a String:​


YA

spam = 'Say hi to Bob\'s mother.'


LI

Double Quote Inside a String:​


spam = "He said, \"Hi!\""
AA

Using Escape Characters in Strings

Here are some practical examples:


# Single quote inside single quotes
spam = 'That\'s Alice\'s cat.'
# Double quote inside double quotes
spam = "He said, \"Hello!\""
# Backslash

Aaliya Waseem,Dept.AIML,JNNCE
2
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

path = 'C:\\Users\\Alice'
# New line
poem = 'Roses are red,\nViolets are blue.'
# Tab
tabbed_text = 'Name\tAge\tLocation'

Conclusion

●​ Single and Double Quotes: Used to create strings.

E
●​ Escape Characters: Allow special characters like quotes, backslashes, and new lines inside

C
strings.

N
This makes it easy to include complex text in Python strings without errors.

JN
2. RAW STRINGS MULTILINE STRINGS

Raw Strings: A raw string is a string where Python ignores all escape characters. This means that

L,
backslashes are treated as part of the string, not as escape characters.

IM
Why use raw strings? When working with strings that contain many backslashes, such as file paths or
regular expressions.
,A
Example of a Raw String:
M

print(r'C:\Users\Al\Desktop')
EE

Output: C:\Users\Al\Desktop
AS

In this case, the \n, \t, and \ characters are treated as part of the string rather than special escape characters.

Multiline Strings: Sometimes you need a string that spans multiple lines. Instead of using multiple \n
W

characters, you can use triple quotes.


YA

●​ Begins and ends with three single quotes ''' or three double quotes """.
●​ All lines within the triple quotes are considered part of the string.
LI

Example of a Multiline String:


AA

print('''Hello,
This is a multiline string example.
You can include newlines, single quotes, and double quotes.''')

Output:​
Hello,
This is a multiline string example.
You can include newlines, single quotes, and double quotes.

Aaliya Waseem,Dept.AIML,JNNCE
3
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

You can also escape quotes inside multiline strings, but it’s optional:

print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

Output:​
Dear Alice,

E
Eve's cat has been arrested for catnapping, cat burglary, and extortion.

C
Sincerely,
Bob

N
JN
Using Triple Quotes for Comments: Multiline strings can also be used for comments that span multiple
lines.

Example:

L,
IM
# Regular comment
print('Hello!') # This is a single-line comment
,A
# Multiline comment using triple quotes
""This is a test Python program.
M

This is useful when you need to write long explanations or document a program in a more detailed way””
EE

3. INDEXING AND SLICING STRINGS


AS

Think of a string as a line of letters, numbers, or symbols. For example:​


"Hello, world!"
W

Each character in the string has a position number called an index. These start at 0 for the first
character, then go 1, 2, 3, and so on.
YA

Here’s how the string "Hello, world!" looks with its index numbers:
LI
AA

Accessing Single Characters

If you want to grab just one character, you can use its index like this:

Aaliya Waseem,Dept.AIML,JNNCE
4
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

spam = "Hello, world!"

print(spam[0]) # Gets 'H', the character at position 0

print(spam[4]) # Gets 'o', the character at position 4

print(spam[-1]) # Gets '!', the last character

Slicing (Getting Parts of the String)

E
C
You can also take parts of the string by slicing it. To slice, you give a starting index and an ending
index like this:

N
print(spam[0:5]) # Gets characters from position 0 to 4: 'Hello'

JN
●​ The starting index is included.
●​ The ending index is not included.

L,
So spam[0:5] means:​

IM
Start at position 0 (H), go up to (but not include) position 5.
,A
Shortcuts for Slicing
M

If you don’t give a starting or ending index, Python assumes some defaults:
EE

●​ spam[:5] means “start at the beginning, stop at position 5.”


●​ spam[7:] means “start at position 7, go to the end.”
AS

Example: print(spam[:5]) # 'Hello' (start from the beginning)

print(spam[7:]) # 'world!' (start at position 7)


W

Original String Stays the Same


YA

When you slice a string, Python gives you a copy of the part you asked for. The original string doesn’t
change:
LI

spam = "Hello, world!"


AA

fizz = spam[0:5]
print(fizz) # 'Hello' (just the part you sliced)
print(spam) # 'Hello, world!' (the original string is still the same)

Key Points:

1.​ Strings are like lists of characters, and you can use numbers (indexes) to pick parts of them.
2.​ Indexes start at 0 for the first character.
3.​ Slicing lets you pick parts of the string, from one position to another.

Aaliya Waseem,Dept.AIML,JNNCE
5
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

4.​ The original string doesn’t change when you slice it.

4. THE IN AND NOT IN OPERATORS WITH STRINGS

The in and not in operators let you check if one string is inside another string. These checks give you a
simple True or False answer.

Here’s how it works, step by step:

The in Operator

E
The in operator checks if a smaller string (a substring) is inside a bigger string.​

C
If the smaller string is found, the result is True. If it’s not found, the result is False.

N
Examples:

JN
print('Hello' in 'Hello, World') # True, because 'Hello' is inside 'Hello, World'

L,
print('HELLO' in 'Hello, World') # False, because Python is case-sensitive ('HELLO' ≠ 'Hello')

IM
print('' in 'spam') # True, because an empty string is technically everywhere

The not in Operator


,A
The not in operator checks if a smaller string is not inside a bigger string.​
If the smaller string is not found, the result is True. If it’s found, the result is False.
M

Examples:
EE

print('cats' not in 'cats and dogs') # False, because 'cats' *is* inside 'cats and dogs'
AS

print('fish' not in 'cats and dogs') # True, because 'fish' is not in 'cats and dogs'

Key Things to Remember:


W

1.​ Case matters: 'Hello' and 'HELLO' are not the same.
2.​ Spaces count: 'Hello ' in 'Hello, World' would be False because of the extra space.
YA

3.​ The result is always True or False (Boolean).

Think of it as asking:
LI

●​ in: "Does this piece exist in that string?"


AA

●​ not in: "Is this piece missing from that string?

5. PUTTING STRINGS INSIDE OTHER STRINGS

Putting strings inside other strings is a common task in Python. Here are three simple ways to do it:

1. Using + (Concatenation)

You join strings using the + operator, but you must convert numbers to strings with str():

Aaliya Waseem,Dept.AIML,JNNCE
6
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

name = 'Al'

age = 4000

print('Hello, my name is ' + name + '. I am ' + str(age) + ' years old.')

# Output: Hello, my name is Al. I am 4000 years old.

2. Using %s (String Interpolation)

E
The %s acts as a placeholder for values. Put the values in a tuple ( ) after the string:

C
name = 'Al'

N
age = 4000

JN
print('My name is %s. I am %s years old.' % (name, age))

# Output: My name is Al. I am 4000 years old.

L,
3. Using f-strings (Best and Easiest)

IM
Start the string with f and use {} to insert variables or expressions directly:
,A
name = 'Al'
M

age = 4000
EE

print(f'My name is {name}. Next year I will be {age + 1}.')

# Output: My name is Al. Next year I will be 4001.


AS

Key Point:
W

●​ Use f-strings for simplicity and readability. Don’t forget the f before the string

6. USEFUL STRING METHODS


YA

Here’s an easy guide to some helpful string methods, with examples to make things clear!
LI

1. Changing Case
AA

●​ upper(): Converts all letters to uppercase.


●​ lower(): Converts all letters to lowercase.

Examples:

text = "Hello, World!"

print(text.upper()) # 'HELLO, WORLD!'

print(text.lower()) # 'hello, world!'

Aaliya Waseem,Dept.AIML,JNNCE
7
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Note: These methods don’t change the original string. If you want to save the result, assign it to a
variable:

text = text.upper() # Saves the uppercase version in the same variable

2. Checking Case

●​ isupper(): Checks if all letters are uppercase.


●​ islower(): Checks if all letters are lowercase.

E
Examples:

C
print("HELLO".isupper()) # True

N
print("hello".islower()) # True

JN
print("Hello123".islower()) # False (not all letters are lowercase)

3. String Validation Methods (isX)

L,
These methods check what a string is made of. They return True or False.

●​
IM
isalpha(): Only letters, no spaces or numbers.
,A
●​ isalnum(): Letters and numbers only, no spaces.
●​ isdecimal(): Only numbers.
●​ isspace(): Only spaces, tabs, or newlines.
M

●​ istitle(): Each word starts with an uppercase letter.


EE

Examples:

print("hello".isalpha()) # True
AS

print("hello123".isalpha()) # False (contains numbers)


print("hello123".isalnum()) # True
print("12345".isdecimal()) # True
W

print(" ".isspace()) # True


print("This Is Title Case".istitle()) # True
YA

4. Checking Start and End

●​ startswith(): Checks if a string starts with a specific substring.


LI

●​ endswith(): Checks if a string ends with a specific substring.


AA

Examples:

text = "Hello, world!"


print(text.startswith("Hello")) # True
print(text.endswith("world!")) # True
print(text.endswith("Hello")) # False

5. Combining Methods

You can chain methods together:

Aaliya Waseem,Dept.AIML,JNNCE
8
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

text = "Hello"

print(text.upper().lower().isupper()) # False (ends up as lowercase)

6. Real-Life Examples

Example 1: Case-Insensitive Comparisons


print("How are you?")
feeling = input() # User types: "GREat"
if feeling.lower() == "great":

E
print("I feel great too!")
else:

C
print("I hope your day gets better!")

N
Example 2: Validating Input

JN
while True:
age = input("Enter your age: ")
if age.isdecimal(): # Ensures input is only numbers

L,
break
print("Please enter a valid number.")

IM
while True:
password = input("Enter a password (letters and numbers only): ")
if password.isalnum(): # Ensures no special characters or spaces
,A
break
M

print("Passwords can only have letters and numbers.")


EE
AS
W
YA
LI
AA

1. The join() Method

Aaliya Waseem,Dept.AIML,JNNCE
9
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

The join() method combines a list of strings into a single string, inserting a specified string between each
item.

How It Works:

●​ Called on a string: The string specifies what goes between each list item.
●​ Pass a list: Provide the list of strings you want to combine.

Examples:

E
# Join with a comma and space

C
print(', '.join(['cats', 'rats', 'bats'])) # Output: 'cats, rats, bats'

N
# Join with a space

JN
print(' '.join(['My', 'name', 'is', 'Simon'])) # Output: 'My name is Simon'

# Join with 'ABC'

L,
print('ABC'.join(['My', 'name', 'is', 'Simon'])) # Output: 'MyABCnameABCisABCSimon'

Key Points:
IM
,A
●​ The string (', ', ' ', 'ABC') is inserted between each list item.
●​ The list must only contain strings, or you’ll get an error.
M

2. The split() Method


EE

The split() method breaks a string into a list of smaller strings. By default, it splits wherever there’s
whitespace (spaces, tabs, newlines).
AS

How It Works:
W

●​ Called on a string: The string is the one you want to split.


●​ Returns a list: Breaks the string into parts.
YA

Examples:

# Split by spaces (default)


LI

print('My name is Simon'.split()) # Output: ['My', 'name', 'is', 'Simon']


AA

# Split by a custom string ('ABC')

print('MyABC name ABCABC Simon'.split('ABC')) # Output: ['My', 'name', 'is', 'Simon']

# Split by the letter 'm'

print('My name is Simon'.split('m')) # Output: ['My na', 'e is Si', 'on']

Key Points:

Aaliya Waseem,Dept.AIML,JNNCE
10
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

●​ By default, it splits wherever there’s whitespace.


●​ You can specify a delimiter (like 'ABC' or 'm') to split the string in a specific way.

3. Splitting Multiline Strings

The split('\n') method splits a string into a list of lines. Each line ends where there’s a newline (\n).

Example:
spam = '''Dear Alice,
How have you been? I am fine.

E
There is a container in the fridge
that is labeled "Milk Experiment."

C
Please do not drink it.

N
Sincerely,
Bob'''

JN
# Split by newline characters
print(spam.split('\n'))

L,
Output:

IM
[
'Dear Alice,',
'How have you been? I am fine.',
,A
'There is a container in the fridge',
'that is labeled "Milk Experiment."',
'',
M

'Please do not drink it.',


'Sincerely,',
EE

'Bob'
]
Each line becomes an item in the list. Empty lines are included as empty strings ('').
AS
W
YA
LI
AA

The partition() Method

The partition() method splits a string into three parts based on a specific separator string you provide. It
creates a tuple with three parts:

Aaliya Waseem,Dept.AIML,JNNCE
11
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

1.​ Before the separator.


2.​ The separator itself.
3.​ After the separator.

How It Works:

1.​ Call it on a string and provide the separator as an argument.


2.​ The method looks for the first occurrence of the separator.
3.​ Returns a tuple with:
○​ Text before the separator.

E
○​ The separator.
○​ Text after the separator.

C
N
Examples:

JN
# Split using 'w' as the separator

print('Hello, world!'.partition('w'))

L,
# Output: ('Hello, ', 'w', 'orld!')

IM
# Split using 'world' as the separator
,A
print('Hello, world!'.partition('world'))

# Output: ('Hello, ', 'world', '!')


M

If the Separator Appears Multiple Times: The method only splits at the first occurrence of the
EE

separator.

# Split using 'o' as the separator


AS

print('Hello, world!'.partition('o'))
W

# Output: ('Hell', 'o', ', world!')

If the Separator Is Not Found: The whole string is returned as the first part, and the second and third
YA

parts are empty strings.

# Separator 'XYZ' not found


LI

print('Hello, world!'.partition('XYZ'))
AA

# Output: ('Hello, world!', '', '')

Assigning the Results to Variables: You can use multiple assignment to save the three parts in separate
variables.

# Split using a space (' ') as the separator

before, sep, after = 'Hello, world!'.partition(' ')

Aaliya Waseem,Dept.AIML,JNNCE
12
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

# Access the parts

print(before) # Output: 'Hello,'

print(sep) # Output: ' '

print(after) # Output: 'world!'

Why Use Partition()?

E
●​ Quickly divide a string into before, separator, and after parts.
●​ Useful for tasks like splitting a sentence into its components or isolating specific sections of a

C
string.

N
In short, partition() makes it easy to break a string into three useful pieces based on a specific keyword or

JN
character

Justifying Text with rjust(), ljust(), and center()

L,
These methods help you align text neatly by adding extra spaces (or other characters) to the left, right, or

IM
both sides of your string. This is super useful when formatting output like tables or lists. Let’s break it
down:
,A
rjust(): Right-Justify

●​ Adds spaces to the left of the string so the text is pushed to the right.
M

●​ The number you provide is the total length of the new string.
EE

Example:

print('Hello'.rjust(10))
AS

# Output: ' Hello' (5 spaces added on the left to make it 10 characters long)
W

You can also add other characters instead of spaces:

print('Hello'.rjust(10, '*'))
YA

# Output: '*****Hello'
LI

ljust(): Left-Justify
AA

●​ Adds spaces to the right of the string so the text stays on the left.
●​ Again, the number you provide is the total length of the new string.

Example:

print('Hello'.ljust(10))

# Output: 'Hello ' (5 spaces added on the right)

Use custom characters too:

Aaliya Waseem,Dept.AIML,JNNCE
13
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

print('Hello'.ljust(10, '-'))

# Output: 'Hello-----'

center(): Center the Text

●​ Adds spaces (or custom characters) to both sides of the string to center it.
●​ The total length of the resulting string is determined by the number you provide.

Example:

E
print('Hello'.center(10))

C
# Output: ' Hello ' (2 spaces on each side for a total of 10 characters)

N
JN
Use custom characters:

print('Hello'.center(10, '='))

L,
# Output: '==Hello==='

IM
7. PROJECT: ADDING BULLETS TO WIKI MARKUP
,A
This project teaches you how to create a Python program (bulletPointAdder.py) that automates adding
bullet points (*) to the start of each line of text. Here's how it works in simple terms:
M

What the Program Does:


EE

1.​ Take text from the clipboard (the text you copied).
2.​ Add a star (*) at the start of every line.
3.​ Put the modified text back onto the clipboard so you can paste it anywhere.
AS

This is useful if you want to create a bulleted list for something like a Wikipedia article, but don’t want to
add * manually for each line.
W

How It Works:
YA

Step 1: Copy and Paste from the Clipboard

Python has a library called pyperclip that lets you:


LI

●​ Get text from the clipboard using pyperclip.paste().


AA

●​ Put text back onto the clipboard using pyperclip.copy().

Basic setup for the program:

import pyperclip

text = pyperclip.paste() # Get text from clipboard

# TODO: Modify the text to add bullets

Aaliya Waseem,Dept.AIML,JNNCE
14
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

pyperclip.copy(text) # Put the modified text back on the clipboard

Step 2: Add Bullets to Each Line

The clipboard text is a single long string, but we want to:

1.​ Break it into separate lines.


2.​ Add a star (*) to the start of each line.

Use the split('\n') method to split the text into a list of lines:t

E
lines = text.split('\n') # Break text into a list of lines

C
Loop through each line and add a star at the start:

N
JN
for i in range(len(lines)): # Loop through each line

lines[i] = '* ' + lines[i] # Add "* " at the start of each line

L,
Step 3: Combine the Lines Back Together

IM
Now that every line starts with a star, combine them back into a single string using '\n'.join(lines):
,A
text = '\n'.join(lines) # Combine the list into a single string with newlines

Step 4: Update the Clipboard


M

Finally, put the modified text (with bullets) back onto the clipboard so it’s ready to paste:
EE

pyperclip.copy(text) # Copy the modified text back to the clipboard


AS

Final Code:

Here’s the complete program:


W

import pyperclip
YA

# Get text from clipboard

text = pyperclip.paste()
LI

# Add a star to the start of each line


AA

lines = text.split('\n') # Split text into lines

for i in range(len(lines)): # Loop through each line

lines[i] = '* ' + lines[i] # Add a star to the start of the line

# Join the lines back into a single string

text = '\n'.join(lines)

Aaliya Waseem,Dept.AIML,JNNCE
15
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

# Copy the modified text back to the clipboard

pyperclip.copy(text)

Why This is Useful:

You can adapt this program to:

●​ Remove spaces.
●​ Add numbers or custom symbols.

E
●​ Change the format of your text for specific tasks.

C
8. PROJECT : PASSWORD LOCKER

N
1. Start

JN
●​ The program begins its execution.

L,
2. Check Command-Line Arguments

IM
●​ The program checks if you have provided the account name (the account you want the password
for) as an input.
●​ If no account name is provided:
,A
○​ The program displays a usage message like:​
"Usage: python pw.py [account_name]"​
M

and stops.
●​ If an account name is provided, it moves to the next step.
EE

3. Look Up the Account


AS

●​ The program checks whether the provided account name exists in the password dictionary (where
all accounts and their passwords are stored).
W

4. Does the Account Exist?

●​ Yes: If the account exists:


YA

○​ The program copies the password to the clipboard using the pyperclip module.
○​ It also prints a message like:​
"Password for [account_name] copied to clipboard!"
LI

●​ No: If the account doesn't exist:


○​ The program displays a message:​
AA

"There is no account named [account_name]"

5. End

●​ After the above steps, the program ends.

Aaliya Waseem,Dept.AIML,JNNCE
16
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Why Is This Useful?

●​ You don’t need to memorize complex passwords.


●​ Just run this script and paste the password where needed.
●​ Safe and efficient for managing multiple accounts!

Scenario: Using the Password Locker

You Have Multiple Accounts Imagine you have passwords for different accounts like:

E
○​ Email: email123password
○​ Facebook: fb_secure2025

C
○​ Twitter: tweet@secure!

N
You don’t want to memorize all these passwords. Instead, you’ve written a Python program called pw.py

JN
to store and retrieve these passwords securely.

How It Works: The program has a dictionary where the account names (like "email", "facebook",
"twitter") are the keys, and their passwords are the values.

L,

IM
PASSWORDS = {
"email": "email123password",
,A
"facebook": "fb_secure2025",
"twitter": "tweet@secure!"
}
M

Example: Retrieving a Password Let’s say you need the password for your Facebook account.​
EE

Steps

Open the terminal and type:​


AS

python pw.py facebook

Here, "facebook" is the account name you want the password for.
W

What Happens Next?


YA

●​ The program checks if you provided an account name. Since you typed "facebook," it moves
forward.
●​ It looks in the dictionary for the "facebook" account.
LI

●​ Found it! The program copies fb_secure2025 to your clipboard (using the pyperclip module).
AA

The terminal prints:​


Password for facebook copied to clipboard!

You Paste the Password​


Go to the Facebook login page, click the password field, and press Ctrl + V to paste the password.

What If the Account Doesn't Exist? Let’s say you type:​


python pw.py instagram

The program will check for "instagram" in the dictionary but won’t find it.
Aaliya Waseem,Dept.AIML,JNNCE
17
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

The terminal will print:​


There is no account named instagram

What If You Forget to Provide an Account Name? If you just type: python pw.py

The program will notice you didn’t provide an account name and print:​
Usage: python pw.py [account_name]

This reminds you to include the account name when running the program.

E
Summary

C
Command: python pw.py [account_name]

N
○​ If the account exists: Copies the password and prints a success message.

JN
○​ If the account doesn’t exist: Tells you the account isn’t found.
○​ If no account name is provided: Shows usage instructions.

CHAPTER 8

L,
1. READING AND WRITING FILES

IM
Definition: A file path is the location of a file on your computer, like an address that tells your
,A
system where to find it. It consists of:

●​ Filename: The name of the file (e.g., document.txt).


M

●​ Path: The hierarchy of folders that leads to the file (e.g., C:\Users\Al\Documents\document.txt).
EE

Concept
AS
W
YA
LI
AA

1.​ File Extensions:


○​ The part after the last dot in the filename (e.g., .txt, .docx).
○​ Tells what type of file it is (e.g., .docx for Word documents, .png for images).
2.​ Path Structure:
○​ Root Folder: The starting point of the path.
■​ Windows: C:\
■​ macOS/Linux: /

Aaliya Waseem,Dept.AIML,JNNCE
18
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

○​ Folders (Directories): Containers for files and other folders.


■​ Example: C:\Users\Al\Documents means:
■​ C:\: Root folder (drive).
■​ Users: Folder inside the root.
■​ Al: Folder inside Users.
■​ Documents: Folder inside Al.
3.​ Separators:
○​ Windows: Backslash \ separates folders.
○​ macOS/Linux: Forward slash / separates folders.
4.​ Pathlib Module:

E
○​ A Python module to handle paths easily.
○​ Automatically adjusts the separator based on the operating system.

C
○​ Uses the / operator to join paths (even on Windows).

N
Examples

JN
Basic Example of a File Path

L,
●​ Windows: C:\Users\Al\Documents\project.docx
●​ macOS/Linux: /Users/Al/Documents/project.docx

Key Advantages of pathlib


IM
,A
1.​ Cross-Platform:
○​ Works on Windows, macOS, and Linux without worrying about slashes.
2.​ Readable Code:
M

○​ The / operator makes paths easy to join.


EE

3.​ Error Prevention:


○​ Avoids common bugs caused by manually adding slashes or using os.path.
AS

1. Understanding Files and Paths

●​ Filename: The name of the file (e.g., projects.docx).


W

●​ Path: The location of the file on your computer, which includes the folder hierarchy. In Windows,
a path might look like C:\Users\asweigart\Documents\projects.docx. In other operating systems
like macOS or Linux, paths have a similar structure but may use different slashes (/).
YA

2. Choosing a File Format


LI

●​ Decide the format of the file. Common formats include:


○​ Text files (.txt)
AA

○​ Comma-separated values files (.csv)


○​ Excel files (.xlsx)
○​ JSON files (.json)
○​ Binary files (.bin)

3. Creating or Opening a File

Creating a New File: Use functions or methods to create a new file.

Aaliya Waseem,Dept.AIML,JNNCE
19
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Example (in Python):​



with open('filename.txt', 'w') as file:
file.write('Initial content')

Opening an Existing File:Use functions or methods to open an existing file and perform read or write
operations.

Example (in Python):​


E
with open('filename.txt', 'r') as file:
content = file.read()

C
N
4. Writing Data to a File: After opening a file in write mode ('w'), data can be written using functions
like write() or writelines().

JN
Example:​
with open('filename.txt', 'w') as file:
file.write('Hello, world!')

L,
5. Appending to a File: Use 'a' mode to append data to an existing file.

Example:​
IM
,A

with open('filename.txt', 'a') as file:
file.write('\nAppended text')
M

6. Reading Data from a File: Use read modes ('r', 'rb' for binary) to read data from files.
EE

Example:​
with open('filename.txt', 'r') as file:
AS

content = file.read()

7. Handling File Paths


W

●​ Ensure paths are correctly specified based on the operating system (Windows, macOS, Linux).
●​ Example:
YA

○​ Windows path: C:\Users\username\Documents\filename.txt


○​ macOS/Linux path: /Users/username/Documents/filename.txt
LI

8. Closing the File: Always close the file after reading or writing operations to free up system resources.
AA

Example:​
file.close()

9. Error Handling: Handle errors such as file not found or permissions issues.

Example:​

try:
with open('filename.txt', 'r') as file:

Aaliya Waseem,Dept.AIML,JNNCE
20
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

content = file.read()
except FileNotFoundError:
print("File not found.")

By following these steps, data can be stored in files and accessed or modified as needed even after the
program has stopped running.

2. THE CURRENT WORKING DIRECTORY

Current Working Directory (cwd): Current Working Directory (cwd): This is the location from which a

E
program starts working. Any files or directories you refer to will be relative to this location unless a full
path is given.

C
N
Examples:

JN
os.getcwd() returns the current working directory.​
import os

L,
os.getcwd()

IM
Changing the current working directory with os.chdir('path'):​

os.chdir('C:\\Windows\\System32')
,A
If a file is named project.docx and your cwd is C:\Python34, then project.docx refers to
C:\Python34\project.docx.
M

Error Example: Trying to change to a non-existent directory will result in an error.​


EE


os.chdir('C:\\ThisFolderDoesNotExist')
AS

Absolute vs. Relative Paths

1.​ Absolute Path:


W

○​ Starts from the root folder (e.g., C:\Users\username\Documents\file.txt).


2.​ Relative Path:
○​ Starts from the current working directory.
YA

○​ Example: project.docx if cwd is C:\Python34.

Dot (.) and Dot-dot (..)


LI

1.​ Dot (.): Refers to "this directory" (the current directory).


AA

○​ Example: .\myfile.txt refers to C:\Python34\myfile.txt when cwd is C:\Python34.


2.​ Dot-dot (..): Refers to "the parent folder" (the directory one level above).
○​ Example: ..\myfile.txt when cwd is C:\Python34 refers to C:\myfile.txt.

Summary

●​ Current Working Directory (cwd) is where Python looks for files by default.
●​ Absolute Path includes the full path (e.g., C:\path\to\file.txt).
●​ Relative Path starts from cwd and uses . or .. to navigate directories.

Aaliya Waseem,Dept.AIML,JNNCE
21
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

E
C
N
JN
L,
3. OS PATH MODULE

IM
The os.path module in Python provides a variety of helpful functions for working with file paths. Let’s
break it down in an easy way with simple scenarios:
,A
1. Working with Absolute and Relative Paths
M

●​ Absolute Path: A full path from the root directory (e.g., C:\Users\username\Documents\file.txt).
●​ Relative Path: A path relative to the current working directory (e.g., file.txt if your cwd is
EE

C:\Users\username\Documents).

Scenario: Suppose you have a Python project and your current working directory (cwd) is C:\Python34.
AS

You want to get the absolute path of a folder named Scripts:​


import os
W

print(os.path.abspath('.\\Scripts'))
YA

Output: C:\Python34\Scripts

2. Checking if a Path is Absolute: Use os.path.isabs(path) to check if a path is absolute.


LI

Scenario:You have a relative path ./Scripts and want to check if it’s absolute:​
AA


import os

print(os.path.isabs('./Scripts'))

Output: False

Now, if you convert it to an absolute path:​


print(os.path.isabs(os.path.abspath('./Scripts')))

Aaliya Waseem,Dept.AIML,JNNCE
22
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Output: True

3. Relative Paths: Use os.path.relpath(path, start) to get a relative path from a starting point.

Scenario:

If you want a relative path from C:\ to C:\Windows:​


print(os.path.relpath('C:\\Windows', 'C:\\'))

Output: 'Windows'

E
Now, if you want to go from C:\spam\eggs to C:\Windows:​

C
print(os.path.relpath('C:\\Windows', 'C:\\spam\\eggs'))

N
Output: '..\\..\\Windows' (moving up two directories)

JN
4. Getting Directory Name and Base Name

●​ os.path.dirname(path) gives you everything before the last slash.

L,
●​ os.path.basename(path) gives you everything after the last slash.

IM
Scenario:
,A
You have a file path C:\Windows\System32\calc.exe:​

import os
M

path = 'C:\\Windows\\System32\\calc.exe'
print(os.path.dirname(path))
EE

print(os.path.basename(path))
Output:
AS

○​ C:\Windows\System32
○​ calc.exe
W

5. Combining Directory and Base Name: Use os.path.split(path) to get a tuple of the directory and base
name.
YA

Scenario:

Using C:\Windows\System32\calc.exe:​
LI


import os
AA

calcFilePath = 'C:\\Windows\\System32\\calc.exe'
print(os.path.split(calcFilePath))
●​ Output:
○​ Directory: C:\Windows\System32
○​ Base name: calc.exe

6. Splitting a Path: path.split(os.path.sep) splits a path into its components based on the system’s file
separator (os.sep).

Scenario:
Aaliya Waseem,Dept.AIML,JNNCE
23
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

On Windows:​

print(calcFilePath.split(os.path.sep))
●​ Output: ['C:', 'Windows', 'System32', 'calc.exe']
On macOS or Linux:​

print('/usr/bin'.split(os.path.sep))
●​ Output: ['', 'usr', 'bin']

Summary

E
●​ Absolute Paths: Full paths from the root directory.

C
●​ Relative Paths: Paths relative to the current working directory.

N
●​ os.path functions help handle paths easily across different systems, checking if paths are absolute,
creating relative paths, and separating paths into directories and file names.

JN
4. THE FILE READING/WRITING PROCESS

L,
In Python, working with files involves three main steps: opening the file, performing read or write
operations, and then closing the file.

IM
1. Opening a File: To open a file, use the open() function.
,A
Syntax: file = open('filename.txt', mode)

mode can be:


M

●​ 'r' for read (default mode).


EE

●​ 'w' for write (creates a new file or overwrites if the file already exists).
●​ 'a' for append (adds content to the end of the file).
AS

Scenario: Opening a file in read mode:​



file = open('example.txt', 'r')
W

2. Reading/Writing the File


YA

Once the file is opened, use methods like read() or write() to interact with it.

Reading from a file:


LI

read() reads the entire file content as a string.​


AA


content = file.read()
print(content)

Writing to a file:

write(data) writes data into the file.​



file.write('Hello, world!')

Aaliya Waseem,Dept.AIML,JNNCE
24
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Scenario: Reading from a file:​



file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

Writing to a file:​

file = open('example.txt', 'w')

E
file.write('New content')
file.close()

C
N
3. Closing the File: Always close the file after you finish reading or writing to it to free up system
resources.​

JN

file.close()

L,
Scenario: After writing or reading:​

IM
file = open('example.txt', 'r')
content = file.read()
print(content)
,A
file.close()

Summary
M

To work with files in Python:


EE

1.​ Open the file using open('filename', mode).


2.​ Read or Write data using read() or write(data).
AS

3.​ Close the file with file.close().

This process handles plaintext files such as .txt or .py files, where content is simple text.
W

5. OPENING AND READING FILES IN PYTHON


YA

In Python, you can open files using the open() function. Let's break it down step by step with simple
examples.
LI

1. Opening a File
AA

To open a file:

●​ Use open('path_to_file') where path_to_file can be an absolute or relative path.


●​ For example, to open a file named hello.txt stored in your user home folder:
○​ Windows: open('C:\\Users\\your_home_folder\\hello.txt')
○​ MacOS/Unix: open('/Users/your_home_folder/hello.txt')

Example:

Aaliya Waseem,Dept.AIML,JNNCE
25
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

●​ On Windows: helloFile = open('C:\\Users\\asweigart\\hello.txt')


●​ On MacOS: helloFile = open('/Users/asweigart/hello.txt')

2. Reading Files

Once you have a File object, you can use different methods to read its contents:

a) read() Method

●​ read() reads the entire file as a single string.

E
Example:

C
N
helloFile = open('hello.txt')
helloContent = helloFile.read()

JN
print(helloContent)

Output:​
Hello world!

L,
b) readlines() Method

IM
●​ readlines() reads the file line by line and returns a list of strings, where each string represents a
,A
line.

Example:
M

Creating sonnet29.txt with four lines:​


EE


When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
AS

And trouble deaf heaven with my bootless cries,


And look upon myself and curse my fate,
Reading the file with readlines():​
W


sonnetFile = open('sonnet29.txt')
sonnetLines = sonnetFile.readlines()
YA

print(sonnetLines)

Output:
LI

['When, in disgrace with fortune and men\'s eyes,\n', ' I all alone beweep my outcast state,\n', ' And trouble
AA

deaf heaven with my bootless cries,\n', ' And look upon myself and curse my fate,\n']

3. Closing the File: After you're done reading or writing to a file, always remember to close it to free up
system resources:

helloFile.close()

Summary

●​ Use open('path') to open a file.

Aaliya Waseem,Dept.AIML,JNNCE
26
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

●​ Use read() to get the entire content as a string.


●​ Use readlines() to get a list of lines from the file.
●​ Always close the file with close() after you're done

6. SAVING VARIABLES WITH THE SHELVE MODULE

The shelve module in Python makes it easy to save and load data from your program so it doesn't get lost
when you close the program. It works like a magic storage box that saves data to your computer and lets
you retrieve it later.

E
Here’s how it works in simple terms:

C
Saving Data:

N
●​ You create a "shelf" (a special storage object) by calling shelve.open() and giving it a filename.

JN
This creates some hidden files on your computer to store the data.
●​ You can store your data in the shelf just like you’d store items in a dictionary. For example, you
can save a list of cat names using a key like 'cats'.

L,
●​ After saving your data, you must close the shelf to make sure everything is saved properly.

IM
Example:​

import shelve
,A
shelfFile = shelve.open('mydata') # Open a shelf file named 'mydata'
cats = ['Zophie', 'Pooka', 'Simon'] # List of cat names
shelfFile['cats'] = cats # Save the list using the key 'cats'
M

shelfFile.close() # Close the shelf


EE

Loading Data:

●​ You can open the shelf again later and retrieve the data using the same key.
AS

●​ The data you saved earlier will still be there, even after restarting your program or computer!

Example:​
W

import shelve
shelfFile = shelve.open('mydata') # Open the same shelf file
print(shelfFile['cats']) # Get the list of cats
YA

shelfFile.close() # Close the shelf


LI

Extra Features:
AA

●​ The shelf acts like a dictionary. You can use .keys() to see all the keys or .values() to see all the
saved data.
●​ If you want the keys or values as a real list, wrap them in list().

Example:​

import shelve
shelfFile = shelve.open('mydata') # Open the shelf
print(list(shelfFile.keys())) # See all the keys
print(list(shelfFile.values())) # See all the values

Aaliya Waseem,Dept.AIML,JNNCE
27
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

shelfFile.close()

How It Works:

When you use shelve, it creates some hidden files (.bak, .dat, .dir on Windows or .db on Mac/Linux) to
store your data. These files are handled automatically, so you don’t need to worry about them.

Why Use a Shelve? It’s perfect for saving data that your program might need later, like settings, game
progress, or lists of items. It’s like saving notes in a file but easier because Python takes care of the tricky
parts for you!

E
Example for understanding purpose:

C
N
Imagine you’re running a cooking club and want to keep track of your favorite recipes. You don’t want to
write them down every time you reopen your notebook. Instead, you want to save them in a "digital box"

JN
that remembers them for you.

Day 1: Adding Recipes You decide to save some of your favorite recipes:

L,
●​ Spaghetti Carbonara

IM
●​ Chocolate Cake
●​ Caesar Salad
,A
You write these recipes down and store them in a special box (the shelve module). Once the recipes are
safely saved, you lock the box and leave for the day.
M

Day 2: Checking the Recipes The next day, you want to see the recipes you saved. You unlock the box,
look inside, and find your list exactly as you left it:
EE

●​ Spaghetti Carbonara
●​ Chocolate Cake
AS

●​ Caesar Salad

The box has remembered everything you stored the previous day!
W

Day 3: Adding a New Recipe You come across a new recipe for Banana Bread and decide to add it to
your collection. You unlock the box, add "Banana Bread" to the list, and lock it again.
YA

Now your collection looks like this:


LI

●​ Spaghetti Carbonara
AA

●​ Chocolate Cake
●​ Caesar Salad
●​ Banana Bread

Day 4: Showing the Recipes to a Friend Your friend asks about your recipes. You unlock the box, take
out the list, and show them:

●​ Spaghetti Carbonara
●​ Chocolate Cake
●​ Caesar Salad

Aaliya Waseem,Dept.AIML,JNNCE
28
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

●​ Banana Bread

Key Points in This Scenario

1.​ The Box = Shelve Module​


The box acts like a storage container for your data (recipes), saving it securely so you don’t lose it
when you stop working.
2.​ Unlocking and Locking = Opening and Closing the Shelf​
To access your saved data, you open the box. When you're done, you close it to ensure everything
stays safe.

E
3.​ Persistence​
No matter how many days pass or how many times you open and close the box, the data you’ve

C
stored remains unchanged unless you update it.

N
4.​ Flexibility​
You can add new recipes, view the existing ones, or even remove some if you no longer need

JN
them.

This scenario shows how the shelve module can be used to save and retrieve data in your programs, just

L,
like storing and managing items in a box.

IM
7. SAVING VARIABLES WITH THE PPRINT.PFORMAT() FUNCTION

The pprint.pformat() function in Python helps save data in a clean, easy-to-read format as Python code.
,A
Here's how it works, step by step:

1.​ Pretty Formatting:


M

○​ It turns your data (like a list or dictionary) into a string that looks neat and is valid Python
code.
EE

2.​ Saving as a Python File:


○​ You can write this formatted string to a .py file. This creates a Python script that stores
your data.
AS

3.​ Using the Saved Data:


○​ Later, you can import the .py file as a module to access the saved data, just like any other
Python script.
W

Example in Simple Terms:


YA

●​ You have a list of cats with names and descriptions.


●​ You save this list to a file called myCats.py using pprint.pformat().
LI

●​ Now, whenever you need that data, you can import myCats and use the list in your programs.
AA

Why Use This?

●​ Readable & Editable: The saved data is plain text, so you can open and edit it with any text editor.
●​ Limitations: This method works only for simple data types (e.g., numbers, strings, lists,
dictionaries) but not for complex objects like open files.

For most cases, shelve is better for saving data, but this method is handy when you need human-readable
and editable files.

Aaliya Waseem,Dept.AIML,JNNCE
29
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Example: Imagine you have a list of fruits and want to save it for later use in your programs.

Step 1: Save the List to a .py File

import pprint
# A list of fruits
fruits = ['apple', 'banana', 'cherry']
# Save the list to a Python file
with open('myFruits.py', 'w') as file:
file.write('fruits = ' + pprint.pformat(fruits) + '\n')

E
This creates a file called myFruits.py, and its content will look like this:
fruits = ['apple', 'banana', 'cherry']

C
N
Step 2: Use the Saved List in Another Program

JN
import myFruits
# Access the saved list of fruits
print(myFruits.fruits) # Output: ['apple', 'banana', 'cherry']
# Use the list

L,
for fruit in myFruits.fruits:

IM
print(f"I love {fruit}!")

Output:
,A
['apple', 'banana', 'cherry']
I love apple!
M

I love banana!
I love cherry!
EE

Why is This Useful?


AS

●​ The list is saved in a file you can import and reuse in other programs.
●​ You can open myFruits.py in any text editor to view or edit the fruits list.
W

8. PROJECT: GENERATING RANDOM QUIZ FILES

Imagine you're a teacher and you want to create unique quiz files for your students so they can’t copy
YA

each other’s answers. Here’s how you can do it step by step using Python:

Step 1: Set Up the Data


LI

First, you create a dictionary that contains the states and their capitals:
AA

capitals = {

'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
# ... more states and capitals ...
}
This is the "question bank" for your quiz.

Aaliya Waseem,Dept.AIML,JNNCE
30
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Step 2: Prepare to Create Quizzes

Decide how many quizzes you want (e.g., 35 quizzes). For each quiz, you:

1.​ Open a file to save the quiz.


2.​ Open another file to save the answer key.

Step 3: Randomize the Questions

Use Python’s random.shuffle() to randomize the order of states:

E
import random

C
states = list(capitals.keys()) # Get the list of states

N
random.shuffle(states) # Shuffle them randomly
This ensures every quiz has questions in a different order.

JN
Step 4: Create Questions and Options

For each question:

L,
1.​ Pick the correct capital for the state.

IM
2.​ Randomly select three wrong answers from the list of all capitals.
3.​ Combine the correct answer and wrong answers into a list.
,A
4.​ Shuffle the list so the correct answer isn’t always in the same position.

Example:
M

correct_answer = capitals[state] # Correct answer


EE

wrong_answers = random.sample([c for c in capitals.values() if c != correct_answer], 3)


answer_options = wrong_answers + [correct_answer]
random.shuffle(answer_options)
AS

Step 5: Write the Quiz


W

Write each question to the quiz file:

quizFile.write(f"{question_num + 1}. What is the capital of {state}?\n")


YA

for i, option in enumerate(answer_options):


LI

quizFile.write(f" {'ABCD'[i]}. {option}\n")


AA

quizFile.write("\n")

Step 6: Write the Answer Key

Save the correct answer to the answer key file:

correct_letter = 'ABCD'[answer_options.index(correct_answer)]

answerKeyFile.write(f"{question_num + 1}. {correct_letter}\n")

Aaliya Waseem,Dept.AIML,JNNCE
31
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

Step 7: Repeat for All Questions and Quizzes

Repeat the above steps for all 50 states in each quiz and for all 35 quizzes.

Step 8: Run the Program

After running the program, you’ll have:

●​ 35 quiz files with randomized questions and options (e.g., capitalsquiz1.txt, capitalsquiz2.txt).
●​ 35 answer key files with the correct answers (e.g., capitalsquiz_answers1.txt,

E
capitalsquiz_answers2.txt).

C
Why Is This Useful?

N
●​ Unique Quizzes: Prevent cheating by randomizing questions and answers.

JN
●​ Easy to Create: Python automates repetitive work.
●​ Reusable: You can update the data (e.g., new states or topics) and generate new quizzes easily.

This way, Python helps you create professional, randomized quizzes quickly

L,
9. PROJECT: MULTI CLIPBOARD

1. What is a Multiclipboard?
IM
,A
A multiclipboard is a program that allows you to save multiple pieces of text with keywords and quickly
retrieve them whenever needed. Think of it as a clipboard with superpowers, where you can store several
M

pieces of text at once and retrieve any of them using specific names (keywords).
EE

2. What Does This Program Do?

●​ Save the current clipboard content using a keyword.


AS

●​ Retrieve clipboard content by entering the keyword.


●​ List all the saved keywords.
W

3. Tools and Concepts Used

●​ sys.argv: Reads command-line arguments you enter when running the program.
YA

●​ pyperclip: Allows the program to interact with the clipboard (copy/paste).


●​ shelve: A Python module for saving data persistently, like a lightweight database.
LI

4. How It Works (Step by Step)


AA

Step 1: Setting Up the Program

We start by:

1.​ Importing the necessary modules:


○​ sys for reading commands.
○​ pyperclip for clipboard operations.
○​ shelve for saving data.
2.​ Opening a "shelf" file:

Aaliya Waseem,Dept.AIML,JNNCE
32
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

○​ A shelf file acts as a small database where we save keywords and their corresponding
clipboard content.

Step 2: Saving Clipboard Content

When you type the command:

py mcb.pyw save <keyword>

The program:

E
1.​ Checks if the first argument is save and there’s a second argument (<keyword>).

C
2.​ Copies the current clipboard content.

N
3.​ Saves it into the shelf file using <keyword> as the key.

JN
For example:

●​ You copy "Hello, world!" to the clipboard.


●​ Run: py mcb.pyw save greeting

L,
●​ Now "greeting" is saved as the keyword for "Hello, world!"

IM
Step 3: Listing All Keywords
,A
When you type the command:

py mcb.pyw list
M

The program:
EE

1.​ Check if the first argument is list.


2.​ Copies a list of all saved keywords from the shelf file to the clipboard.
AS

3.​ You can paste the list into a text editor to view the keywords.

For example: If you have saved greeting and farewell, running list will copy:
W

['greeting', 'farewell']
YA

Step 4: Retrieving Clipboard Content

When you type the command:


LI

py mcb.pyw <keyword>
AA

The program:

1.​ Checks if the <keyword> exists in the shelf file.


2.​ Copies the text associated with that keyword to the clipboard.

For example:

●​ Run: py mcb.pyw greeting


●​ The text "Hello, world!" is copied back to your clipboard.

Aaliya Waseem,Dept.AIML,JNNCE
33
Introduction to python programming​ ​ ​ ​ ​ ​ ​ BPLCK105B

5. How It All Fits Together

Here’s a quick summary of what happens based on your input:

1.​ Save: Stores clipboard text under a keyword.


2.​ List: Copies all keywords to the clipboard.
3.​ Retrieve: Copies the saved text for a specific keyword to the clipboard.

6. Why is This Useful?

E
●​ Automates repetitive tasks, such as filling out forms.
●​ Saves time when working with frequently used text snippets.

C
●​ Makes it easy to organize and manage multiple pieces of clipboard content.

N
JN
L,
IM
,A
M
EE
AS
W
YA
LI
AA

Aaliya Waseem,Dept.AIML,JNNCE
34

You might also like