0% found this document useful (0 votes)
1 views8 pages

Module3 File Handling Study Guide

This document serves as an exam preparation guide for Python, focusing on file handling and string methods. It outlines key topics, their frequency in past exams, and provides essential information about file operations, the shelf module, string handling methods, and the OS module. Each section includes example code and explanations to aid understanding and preparation.

Uploaded by

nandanbs2006
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)
1 views8 pages

Module3 File Handling Study Guide

This document serves as an exam preparation guide for Python, focusing on file handling and string methods. It outlines key topics, their frequency in past exams, and provides essential information about file operations, the shelf module, string handling methods, and the OS module. Each section includes example code and explanations to aid understanding and preparation.

Uploaded by

nandanbs2006
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

Module 3 — File Handling & String Methods

22POP13 — Exam Preparation Guide (Python Track)

At-a-Glance: Question Frequency Summary


# Topic Repeated Priority

1 File Reading & Writing (open/read/write) 3 ★★★★★

2 Shelf Module (shelve, pprint, pformat) 3 ★★★★★

3 String Handling Methods (split, join, isX, etc.) 3 ★★★★★

4 OS Module Functions 2 ★★★★★

5 Read & Print Text File (readlines, specific lines) 2 ★★★★■

6 upper(), lower(), isupper(), islower() 1 ★★★■■

7 in / not in operators in strings 1 ★★★■■

8 Writing & Reading Lists from File 1 ★★★■■

9 Logging in Python 1 ★★★■■

10 ZIP Files (zipfile module) 1 ★★★■■

Legend: Repeated = number of times this exact topic appeared across past exam papers. Priority stars reflect
overall importance based on frequency + weightage.
1. File Reading and Writing Process in Python
Repeated 3 times Priority: ★★★★★

A file is used to store data permanently on disk. Python can read data from a file and write data into a file using
built-in functions.

Three Main Steps


• Open the file using open()
• Read or write using read() / write()
• Close the file using close()

File Modes

Mode Meaning

r Read mode

w Write mode — old data is deleted

a Append mode — new data is added at the end

Program

# Writing to a file
file = open("[Link]", "w")
[Link]("Name: Nandan\n")
[Link]("Course: Python\n")
[Link]()

# Reading from a file


file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

Output

Name: Nandan
Course: Python

read() reads the full file content as one string. write() writes text into the file. If the file is opened in w mode, old
content is removed; if opened in a mode, new content is added at the end.

2. Shelf Module in Python


Repeated 3 times Priority: ★★★★★

The shelve module is used to save Python variables permanently. It works like a dictionary, storing data using
key-value pairs.

Program
import shelve

# Saving variable
shelfFile = [Link]("mydata")
cats = ["Zophie", "Pooka", "Simon"]
shelfFile["cats"] = cats
[Link]()

# Reading variable
shelfFile = [Link]("mydata")
print(shelfFile["cats"])
[Link]()

Output

['Zophie', 'Pooka', 'Simon']

Here, "cats" is the key and the list is the value. The saved data can be reopened later and reused in another
program — shelf files support both reading and writing after opening.

pprint() and pformat()

Function Purpose

[Link]() Prints lists or dictionaries neatly to the screen

[Link]() Converts the list/dictionary into a string (for writing to a file)

import pprint

cats = [{"name": "Zophie", "desc": "chubby"},


{"name": "Pooka", "desc": "fluffy"}]

fileObj = open("[Link]", "w")


[Link]("cats = " + [Link](cats))
[Link]()

This creates a Python file and stores the variable inside it, ready to be imported later.

3. Python String Handling Methods


Repeated 3 times Priority: ★★★★★

String methods are used to change, check, split, join, or format strings. This is one of the highest-weightage
topics — questions are asked in different combinations each year.

split()
Splits a string into a list.

text = "Python is easy"


print([Link]())

['Python', 'is', 'easy']

join()
Joins list items into one string.
words = ["Python", "is", "easy"]
print(" ".join(words))

Python is easy

startswith()
Checks whether a string starts with the given text.

name = "Python Programming"


print([Link]("Python"))

True

endswith()
Checks whether a string ends with the given text.

file = "[Link]"
print([Link](".pdf"))

True

Alignment Methods: ljust(), rjust(), center()

Method Effect Example Output

ljust(10, "-") Aligns text to the left Hi--------

rjust(10, "-") Aligns text to the right --------Hi

center(10, "-") Aligns text in the center ----Hi----

print("Hi".ljust(10, "-"))
print("Hi".rjust(10, "-"))
print("Hi".center(10, "-"))

strip(), lstrip(), rstrip()

Method Removes spaces from

strip() Both sides

lstrip() Left side only

rstrip() Right side only

text = " hello "


print([Link]())
print(" hello".lstrip())
print("hello ".rstrip())

hello
hello
hello

Note: split() returns a list, join() converts a list back into a single string, and ljust()/rjust()/center() are useful for
formatting neat, aligned output.
4. isX String Methods (Validation Methods)
Part of Repeated 3× String Methods group Priority: ★★★★★

These methods always return either True or False, and are mainly used for input validation.

Method Returns True when... Example

isalpha() String contains only alphabets "Python".isalpha() → True

isalnum() String contains only alphabets and numbers "Python123".isalnum() → True

isdecimal() String contains only numbers "12345".isdecimal() → True

isspace() String contains only spaces/tabs/newlines " ".isspace() → True

istitle() Every word starts with a capital letter "Python Programming".istitle() → True

print("Python".isalpha())
print("Python123".isalpha())
print("Python123".isalnum())
print("12345".isdecimal())
print(" ".isspace())
print("Python Programming".istitle())

Output

True
False
True
True
True
True

5. OS Module Functions
Repeated 2 times Priority: ★★★★★

The os module is used to work with files, folders, and paths.

Function Purpose Example

getcwd() Returns current working directory [Link]()

chdir() Changes current working directory [Link]("C:\\Users")

makedirs() Creates folders and subfolders [Link]("C:\\demo\\python\\files")

listdir() Lists files and folders in a directory [Link]("C:\\Users")

relpath() Returns relative path between two locations [Link]("C:\\Windows","C:\\")

rmdir() Removes an empty folder [Link]("testfolder")

walk() Visits all folders/files inside a directory [Link]("C:\\demo")

walk() — Detailed Example


import os

for folder, subfolders, files in [Link]("C:\\demo"):


print("Folder:", folder)
print("Subfolders:", subfolders)
print("Files:", files)

getcwd() returns the directory Python is currently running in. chdir() changes that directory. makedirs() can
create nested folders in one call, while listdir() only lists — it does not create anything.

6. Program to Read and Print Text File


Repeated 2 times Priority: ★★★★■

file = open("[Link]", "r")


content = [Link]()
print(content)
[Link]()

Reading Specific Lines

file = open("[Link]", "r")


lines = [Link]()

print(lines[0]) # first line


print(lines[1]) # second line

[Link]()

readlines() stores each line of the file as one separate item in a list.

7. upper(), lower(), isupper(), islower()


Asked Only Once — but Important Priority: ★★★■■

Method Effect Example

upper() Converts string to uppercase "hello".upper() → HELLO

lower() Converts string to lowercase "HELLO".lower() → hello

isupper() Checks if all letters are uppercase "HELLO".isupper() → True

islower() Checks if all letters are lowercase "hello".islower() → True

print("hello".upper())
print("HELLO".lower())
print("HELLO".isupper())
print("hello".islower())

Output

HELLO
hello
True
True

upper() and lower() return new strings; they do not change the original string.
8. in and not in Operators in Strings
Asked Only Once Priority: ★★★■■

The in operator checks whether a substring is present in a string.

text = "Python programming"

print("Python" in text)
print("Java" in text)

True
False

The not in operator checks whether a substring is NOT present.

print("Java" not in text)

True

Both operators are case-sensitive — so "python" and "Python" are treated as different strings.

9. Writing and Reading Lists from a File


Asked Only Once Priority: ★★★■■

A list cannot be directly written to a text file — it must first be converted into a string.

Writing a List

students = ["Nandan", "Rahul", "Kiran"]

file = open("[Link]", "w")


for name in students:
[Link](name + "\n")
[Link]()

Reading a List

file = open("[Link]", "r")


students = [Link]()
[Link]()

print(students)

['Nandan\n', 'Rahul\n', 'Kiran\n']

To remove the trailing newline characters:

students = [[Link]() for name in students]


print(students)

['Nandan', 'Rahul', 'Kiran']

10. Logging in Python


Asked Only Once Priority: ★★★■■

Logging is used to record messages while a program runs, helping to debug it. Instead of using many print()
statements, we can use the logging module.
import logging

[Link](level=[Link])

def factorial(n):
[Link]("Start of factorial")
result = 1

for i in range(1, n + 1):


result = result * i
[Link]("i = " + str(i) + ", result = " + str(result))

[Link]("End of factorial")
return result

print(factorial(5))

Logging helps identify exactly where a program is working correctly and where an error occurs.

11. ZIP File in Python


Asked Only Once Priority: ★★★■■

A ZIP file compresses many files into one, saving space and making sharing easy. Python uses the zipfile
module to create and extract ZIP files.

Creating a ZIP File

import zipfile

zipObj = [Link]("[Link]", "w")


[Link]("[Link]")
[Link]("[Link]")
[Link]()

Extracting a ZIP File

import zipfile

zipObj = [Link]("[Link]")
[Link]("extracted_files")
[Link]()

ZIP is useful for compressing, storing, and transferring multiple files easily.

You might also like