[go: up one dir, main page]

0% found this document useful (0 votes)
44 views19 pages

Module 3

The document discusses various file system paths, including absolute and relative paths, and provides examples for each. It also covers reading specific lines from a file using Python, the importance of logging for debugging, creating ZIP files, and implementing multi clipboard functionality. Additionally, it explains how to read and write lists to files, string handling methods, using the shelve module for variable storage, and provides several Python program examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views19 pages

Module 3

The document discusses various file system paths, including absolute and relative paths, and provides examples for each. It also covers reading specific lines from a file using Python, the importance of logging for debugging, creating ZIP files, and implementing multi clipboard functionality. Additionally, it explains how to read and write lists to files, string handling methods, using the shelve module for variable storage, and provides several Python program examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

1. Discuss different paths of file system.

1. Absolute Path

 It describes the complete location of a file or folder from the root directory.

 Always starts from the root of the file system (C:\ on Windows or / on
Unix/Linux).

 It always points to the same file, regardless of where the program is run.

Example (Windows):

path = "C:\\Users\\Ayesha\\Documents\\file.txt"

2. Relative Path

 It describes the location of a file or folder relative to the current working


directory (where the script is run).

 More flexible and portable across different systems or environments.

 Does not start with a root (no / or drive letter at the beginning).

Example:

If your script is in C:\Users\Ayesha\, and the file is in the Documents folder:

path = "Documents\\file.txt"

2. Explain how to read specific lines from a file?. illustrate with


python program
✅ Program to Read Specific Lines from a File

Let's say you have a file called sample.txt like this:


Line 1: Hello
Line 2: Welcome
Line 3: How are you?
Line 4: Goodbye
Now we want to read line 2 and line 4.

🔸 Python Program:
with open("sample.txt", "r") as file:
lines = file.readlines() # reads all lines into a list
print("Line 2:", lines[1]) # Index starts from 0
print("Line 4:", lines[3])

✅ Output:
Line 2: Welcome
Line 4: Goodbye

3. What is logging? how this would be used to debug the python


program?
✅ What is Logging in Python?
Logging is the process of recording events or messages that
happen when a program runs. These messages can help
debug, monitor, or track errors in your code.
Instead of using print() statements, Python's logging module
provides a more powerful and flexible way to handle
messages.

✅ How is Logging Helpful in Debugging a Program?


Logging is very helpful in debugging because it gives a clear,
step-by-step record of what your program is doing during
execution. Here's how it helps:

🔹 1. Tracks Program Flow


Logging shows the sequence of actions taken by the
program. This helps identify where something went wrong.

🔹 2. Captures Variable Values


It can record the values of variables at different stages,
which is useful to check if they're behaving as expected.

🔹 3. Identifies Errors and Exceptions


Logging can capture errors and exceptions with full details
(like error type and message), making it easier to fix bugs.

🔹 4. Provides Context
You can include messages in logs to explain what each part
of the code is doing. This helps you or other developers
understand the logic and identify faulty sections.

🔹 5. No Need to Modify Code Repeatedly


Unlike print() statements, logging doesn't need to be
removed before deployment. You can control what gets
logged using log levels.

🔹 6. Records for Later Review


Logs can be saved to files and reviewed later. This is helpful
for bugs that occur randomly or in production environments.

🔹 7. Supports Different Levels of Detail


Using log levels (DEBUG, INFO, WARNING, etc.), you can
choose how much information you want to see based on the
situation.

4. What is the use of ZIP? how to create a ZIP folder explain.


✅ What is the Use of a ZIP File?

A ZIP file is a compressed folder that stores one or more files or


directories in a smaller size. It is used to:
 Reduce file size to save space.
 Group multiple files into one folder.
 Easily share or transfer files (like sending via email).
 Protect files with optional encryption or password.
✅ How to Create a ZIP Folder in Python?
Python provides a built-in module called zipfile to create, read,
and extract ZIP files.

🔸 Steps to Create a ZIP File:


1. Import zipfile.
2. Use ZipFile() in write ('w') mode.
3. Add files using .write() method.
import zipfile

with zipfile.ZipFile('my_archive.zip', 'w') as zipf:

zipf.write('file1.txt') # Add first file

zipf.write('file2.txt') # Add second file

print("ZIP file created successfully.")


5. wite an algorithm for implement multi clipboard functionality
Step 1: Start
Initialize an empty dictionary to store clipboard entries.

Step 2: Display Menu


Show the user a menu with the following options:

 Save current clipboard content

 Load a saved content

 View all saved clips

 Exit

Step 3: Save Clipboard Content

 Ask user to enter a name for the clip.

 Get the current clipboard text using pyperclip.paste().

 Store it in the dictionary with the given name.

Step 4: Load a Saved Clip

 Ask user for the clip name.

 If it exists in the dictionary, copy the text to the clipboard using


pyperclip.copy().

Step 5: View All Clips

 Display all saved clip names (keys of the dictionary).

Step 6: Repeat Until Exit

 Keep showing the menu until the user chooses to exit.

End

6.Discuss how lists would be written in the file and read from the
file? 8 marks
🔹 1. Introduction
In Python, lists can be stored in a file and read back later. This is useful
for saving data permanently and reusing it.

There are two common methods:

 Using plain text (write, read)

 Using structured formats like JSON

🔹 2. Writing a List to a File

a) Using Plain Text

Each element is written to a file line by line.

my_list = ['apple', 'banana', 'cherry']

with open('fruits.txt', 'w') as file:

for item in my_list:

file.write(item + '\n') # write each item on a new line

🔹 3. Reading a List from a File

a) From Plain Text

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

my_list = [line.strip() for line in file]

7. Explain Python string handling methods with examples: split(),endswith(), ljust(),


center(), lstrip() simple easy

✅ 1. split()

 Use: Splits a string into a list of words or parts.

 Syntax: string.split(separator)

 Default separator is space.

text = "apple banana cherry"

result = text.split()

print(result) # ['apple', 'banana', 'cherry']

python

result = text.split(",")

print(result) # ['a', 'b', 'c']

✅ 2. endswith()

 Use: Checks if the string ends with a specific value.


 Returns: True or False

text = "hello.txt"

print(text.endswith(".txt")) # True

print(text.endswith(".pdf")) # False

✅ 3. ljust()

 Use: Left-justifies the string with spaces (or a character).

 Syntax: string.ljust(width, fillchar)

text = "cat"

print(text.ljust(10)) # 'cat '

print(text.ljust(10, '-')) # 'cat-------'

✅ 4. center()

 Use: Centers the string with spaces (or a fill character).

 Syntax: string.center(width, fillchar)

text = "cat"

print(text.center(10)) #' cat '

print(text.center(10, '*')) # '***cat****'

✅ 5. lstrip()

 Use: Removes leading (left-side) spaces or characters.

 Syntax: string.lstrip(chars)

text = " hello"

print(text.lstrip()) # 'hello'

text2 = "---hello---"

print(text2.lstrip('-')) # 'hello---'

8. Explain reading and saving python program variables using shelve


module with suitable Python program. short simple easy to understand
and memorise

✅ Steps to Use shelve

1. Import the module.

2. Open a shelve file.


3. Save or read variables like a dictionary.

4. Close the shelf.

✅ Example Program

import shelve

with shelve.open('mydata') as db:

db['name'] = 'Ayesha'

db['marks'] = [85, 90, 95]

with shelve.open('mydata') as db:

print(db['name']) # Output: Ayesha

print(db['marks']) # Output: [85, 90, 95]

9. Develop a Python program to read and print the contents of a text file.
small easy

✅ Python Program to Read and Print a Text File

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

content = file.read()

print(content)

Explanation:

 open('example.txt', 'r'): Opens the file in read mode.

 file.read(): Reads the entire content of the file.

 print(content): Prints the content to the console.

10. Explain Python string handling methods with examples: join(),


startswith(),rjust(),strip(),rstrip()

✅ 1. join() SPLIT()

 Use: Joins a sequence (like a list or tuple) of strings into a single


string, with a separator in between.

 Syntax: separator.join(iterable)

 Example:

words = ['Hello', 'World']

result = ' '.join(words) # Joins with a space

print(result) # Output: "Hello World"


✅ 2. startswith()

 Use: Checks if a string starts with the specified prefix.

 Returns: True or False

 Syntax: string.startswith(prefix)

 Example:

text = "Hello World"

print(text.startswith("Hello")) # True

print(text.startswith("World")) # False

✅ 3. rjust()

 Use: Right-justifies the string, adding spaces (or a character) on the


left to fill the specified width.

 Syntax: string.rjust(width, fillchar)

 Example:

text = "cat"

print(text.rjust(10)) #' cat'

print(text.rjust(10, '*')) # '*******cat'

✅ 4. strip()

 Use: Removes leading and trailing whitespace (or characters).

 Syntax: string.strip(chars)

 Example:

text = " Hello World! "

print(text.strip()) # Output: "Hello World!"

✅ 5. rstrip()

 Use: Removes trailing (right-side) whitespace (or characters).

 Syntax: string.rstrip(chars)

 Example:
text = "Hello World! "

print(text.rstrip()) # Output: "Hello World!"

11. Explain with suitable Python program segments: (i) os.path.basename()


(ii) os.path.join(). short simple easy

✅ 1. os.path.basename()

 Use: Returns the base name of a file or directory from a given path. It
removes the directory path and returns just the file or folder name.

 Syntax: os.path.basename(path)

Example:

import os

path = "/home/user/Documents/file.txt"

base_name = os.path.basename(path)

print(base_name) # Output: "file.txt"

✅ 2. os.path.join()

 Use: Joins one or more path components (like folder names or file
names) into a single path. It automatically adds the correct separator
(/ or \) depending on the operating system.

 Syntax: os.path.join(path1, path2, ...)

Example:

import os

folder = "/home/user/Documents"

file_name = "file.txt"

full_path = os.path.join(folder, file_name)

print(full_path) # Output: "/home/user/Documents/file.txt"

12. Develop a Python program find the total size of all the files in the given
dictionary

import os

def get_total_size(directory):

total_size = 0

for filename in os.listdir(directory):


file_path = os.path.join(directory, filename)

if os.path.isfile(file_path): # Check if it's a file

total_size += os.path.getsize(file_path) # Add file size

return total_size

# Example usage

directory = "path/to/your/directory" # Replace with your directory path

size = get_total_size(directory)

print(f"Total size of all files in the directory: {size} bytes")

13. Write the output of following Python code >>>Spam = 'Hello, World!' i)
>>>Spam[0[ ii) >>Spam[4] iii) >>>Spam[-1] iv) Spam[0: 5] v) >>> Spam
[:5] vi)>>>Spam[7 :]

i) Spam[0]

 Explanation: This accesses the first character of the string Spam, which
is 'H'.

 Output: 'H'

ii) Spam[4]

 Explanation: This accesses the character at index 4, which is 'o'


(indices start at 0).

 Output: 'o'

iii) Spam[-1]

 Explanation: This accesses the last character of the string using


negative indexing, which is '!'.

 Output: '!'

iv) Spam[0:5]

 Explanation: This slices the string from index 0 to 5 (not including


index 5), which gives the substring 'Hello'.

 Output: 'Hello'

v) Spam[:5]
 Explanation: This slices the string from the start (default index 0) to 5
(not including index 5), which gives the substring 'Hello'.

 Output: 'Hello'

vi) Spam[7:]

 Explanation: This slices the string starting from index 7 to the end,
which gives the substring 'World!'.

 Output: 'World!'

14. Write a program to accept string and display total number of alphabets.

input_string = input("Enter a string: ")

alphabet_count = sum(1 for char in input_string if char.isalpha())

print(f"Total number of alphabets: {alphabet_count}")

15. Explain how to save variables with the Shelve module.

How to Save Variables with the Shelve Module in Python

The shelve module allows you to store Python objects (such as variables,
dictionaries, lists, etc.) persistently in a file, much like a dictionary. It
automatically handles serialization and deserialization for you. You can save
and retrieve variables without needing to manually handle their format.

Steps to Save Variables Using Shelve:

1. Import the shelve module.

2. Open a shelf (a file-based dictionary).

3. Assign variables to keys in the shelf.

4. Close the shelf after saving.

Example Program: Saving Variables

import shelve

with shelve.open('my_shelve_file') as shelf:

shelf['name'] = 'Alice' # Storing a string

shelf['age'] = 25 # Storing an integer

shelf['marks'] = [85, 90, 95] # Storing a list

shelf['is_student'] = True # Storing a boolean


print("Variables have been saved to the shelve file.")

✅ 1. isalpha()

 Use: Checks if all characters in the string are alphabetic (A-Z or a-z).

 Returns: True if all characters are alphabets, otherwise False.

Example:

text = "Hello"

print(text.isalpha()) # Output: True

text = "Hello123"

print(text.isalpha()) # Output: False

✅ 2. isalnum()

 Use: Checks if all characters in the string are alphanumeric (letters and
digits).

 Returns: True if all characters are alphanumeric, otherwise False.

Example:

text = "Hello123"

print(text.isalnum()) # Output: True

text = "Hello 123"

print(text.isalnum()) # Output: False (space is not allowed)

✅ 3. isdecimal()

 Use: Checks if all characters in the string are decimal digits (0-9).

 Returns: True if all characters are decimal digits, otherwise False.

Example:

text = "12345"

print(text.isdecimal()) # Output: True


text = "123.45"

print(text.isdecimal()) # Output: False (because of the dot)

✅ 4. isspace()

 Use: Checks if all characters in the string are whitespace (spaces, tabs,
etc.).

 Returns: True if all characters are spaces, otherwise False.

Example:

text = " "

print(text.isspace()) # Output: True

text = "Hello World"

print(text.isspace()) # Output: False

✅ 5. istitle()

 Use: Checks if the string is in title case, meaning the first letter of each
word is uppercase and the rest are lowercase.

 Returns: True if the string is in title case, otherwise False.

Example:

text = "Hello World"

print(text.istitle()) # Output: True

text = "hello world"

print(text.istitle()) # Output: False

19. Write a Python program that repeatedly asks users for their age and a
Password until they provide valid input. [age is in digit and Password in
alphabet an digit only].

import re

def get_valid_age():

while True:

age = input("Enter your age: ")


if age.isdigit(): # Check if the age is a valid number

return int(age)

else:

print("Invalid input. Age should be a number.")

def get_valid_password():

while True:

password = input("Enter your password (letters and digits only): ")

if re.match("^[A-Za-z0-9]+$", password): # Check if password contains


only letters and digits

return password

else:

print("Invalid input. Password should contain only alphabets and


digits.")

# Main program

age = get_valid_age()

password = get_valid_password()

print(f"Age: {age}")

print(f"Password: {password}")

20. Differentiate between Absolute and relative paths in specifying file


paths.

Feature Absolute Path Relative Path

Starts From Root directory (C:\, /) Current working directory

C:\Users\Ayesha\Documents\
Example Documents/file.txt
file.txt

More portable (can work


Portability Less portable (specific to system)
across systems)

Dependence Does not depend on the current Depends on the current


on cwd working directory working directory

Use case When exact file location is needed When you want flexibility
Feature Absolute Path Relative Path

to move or share files

21. Explain join() and split() method with examples.

1. join() Method

 Use: The join() method is used to join elements of an iterable (like a


list or tuple) into a single string with a specified separator.

 Syntax: separator.join(iterable)

 How it works: It combines all the elements of the iterable into one
string, with the separator between each element.

Example:

words = ["Hello", "world", "Python"]

result = " ".join(words)

print(result) # Output: "Hello world Python"

2. split() Method

 Use: The split() method is used to split a string into a list based on a
specified separator.

 Syntax: string.split(separator, maxsplit)

 How it works: It divides the string into a list where each element is a
substring separated by the specified separator. If no separator is
specified, it defaults to splitting by any whitespace.

Example:

sentence = "Hello world Python"

words = sentence.split()

print(words) # Output: ['Hello', 'world', 'Python']

22. Develop a python code to determine whether the given string is


palindrome or not a palindrome.

def is_palindrome(s):

s = s.replace(" ", "").lower()

if s == s[::-1]:

return True

else:
return False

input_string = input("Enter a string: ")

if is_palindrome(input_string):

print(f"'{input_string}' is a palindrome!")

else:

print(f"'{input_string}' is not a palindrome.")

23. Explain the concept of file handling. Also explain reading and writing
process with suitable example.

Concept of File Handling in Python

File handling in Python refers to the process of interacting with files on the
system to read, write, and manipulate file data. It involves using various
methods and functions to perform operations on files such as opening,
reading, writing, and closing files.

File Modes:

When opening a file, you specify the mode, which tells Python what type of
operations you want to perform on the file:

 'r': Read (default mode). Opens the file for reading.

 'w': Write. Opens the file for writing (creates a new file if it doesn't
exist).

 'a': Append. Opens the file for appending new data.

 'rb' / 'wb': Binary read/write (for non-text files like images).

Example - Complete Program for Reading and Writing

with open("testfile.txt", "w") as file:

file.write("Hello, World!\n")

file.write("This is a test file.")

with open("testfile.txt", "r") as file:

content = file.read() # Read entire content

print(content)

Output:

Hello, World!

This is a test file.


24. Explain the concept of file path. Also discuss absolute and relative file
path.

File Path

A file path specifies the location of a file in a file system. It is a string of


characters that defines the location of a file or directory, starting from the
root directory to the file or folder.

Types of File Paths:

1. Absolute Path:

o Definition: An absolute path specifies the complete path to a file,


starting from the root directory.

o Key Point: It is fixed and independent of the current working


directory.

o Example:

 Windows: C:\Users\John\Documents\file.txt

 Linux: /home/john/Documents/file.txt

o Advantages: Provides an exact and unambiguous file location.

o Disadvantages: Less portable across systems, as paths are


specific to the OS.

2. Relative Path:

o Definition: A relative path specifies the file location relative to the


current working directory.

o Key Point: It is dynamic and depends on the current directory.

o Example:

 Documents/file.txt (file inside a subdirectory).

 ../file.txt (file in the parent directory).

o Advantages: More portable and flexible across different systems


and directories.

o Disadvantages: Its meaning changes depending on the current


working directory.

25. Briefly explain saving variables with shelve module.

Steps to Save Variables with shelve:

1. Open a Shelf: Use shelve.open() to open a shelf (file-based storage).


2. Store Variables: Assign values to keys just like you would in a
dictionary.

3. Close the Shelf: Close the shelf to ensure that data is saved properly.

Example: Saving and Retrieving Variables with shelve

import shelve

with shelve.open('my_shelve') as shelf:

shelf['name'] = 'Alice'

shelf['age'] = 30

shelf['marks'] = [85, 90, 95]

shelf['is_student'] = True

with shelve.open('my_shelve') as shelf:

print(shelf['name']) # Output: Alice

print(shelf['age']) # Output: 30

print(shelf['marks']) # Output: [85, 90, 95]

print(shelf['is_student']) # Output: True

You might also like