UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 1
Concatenation, Appending, and Multiplying Strings
1. Introduction to Strings (Quick Recall)
A string in Python is:
• A sequence of characters
• Written inside quotes (' ' or " ")
• Immutable (cannot be modified after creation — covered next topic)
Example:
text = "Python"
2. String Concatenation
What is Concatenation?
Concatenation means joining two or more strings together.
Python uses the + operator for concatenation.
Syntax
new_string = string1 + string2
Example 1: Joining Two Strings
a = "Hello"
b = "World"
c = a + b
print(c)
Output
HelloWorld
Example 2: Adding Space Between Words
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Output:
Hello World
Example 3: User Input Concatenation
first = input("Enter first name: ")
last = input("Enter last name: ")
full = first + " " + last
print("Full Name:", full)
Important Rule
Only strings can be concatenated.
❌ Incorrect:
"Age: " + 20
✔ Correct:
"Age: " + str(20)
3. Appending Strings
What is Appending?
Appending means adding a string at the end of another string.
Since strings are immutable, Python actually creates a new string.
Example 4: Appending Text
text = "Python"
text = text + " Programming"
print(text)
Output:
Python Programming
Example 5: Building Sentence Step-by-Step
sentence = ""
sentence += "Python "
sentence += "is "
sentence += "easy."
print(sentence)
Output:
Python is easy.
Note
+= is shorthand for concatenation.
a += b
means
a = a + b
4. Multiplying Strings
What is String Multiplication?
Strings can be repeated using *.
Syntax
string * number
Example 6: Repeating String
text = "Hi "
print(text * 3)
Output:
Hi Hi Hi
Example 7: Printing Line Separator
print("-" * 20)
Output:
--------------------
Example 8: Pattern Generation
print("*" * 5)
Output:
*****
Example 9: Combined Use
name = "Python"
print((name + " ") * 3)
Output:
Python Python Python
5. Real-Time Example
Ticket Printing System
print("=" * 30)
print("Welcome to Booking")
print("=" * 30)
Output:
==============================
Welcome to Booking
==============================
6. Common Beginner Mistakes
Mistake 1: Multiplying Two Strings
"Hi" * "3"
❌ Error
Correct:
"Hi" * 3
Mistake 2: Concatenating String and Number
"Marks: " + 90
❌ Error
Correct:
"Marks: " + str(90)
7. Practice Exercises
1. Join first name and last name using concatenation.
2. Print your name five times using multiplication.
3. Build sentence using +=.
4. Print separator line of 40 stars.
5. Create banner using repeated characters.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 2
Immutability of Strings
In the previous topic, we learned how to join and repeat strings. Now we study an important
property of strings:
Strings in Python are immutable.
Understanding this concept prevents many beginner errors and helps write efficient programs.
1. What is Immutability?
A data type is called immutable if its value cannot be changed after creation.
In Python:
Data Type Mutable?
List Mutable
Dictionary Mutable
Set Mutable
Tuple Immutable
String Immutable
2. Meaning of String Immutability
Once a string is created:
• Its characters cannot be modified
• Python creates a new string instead of modifying the existing one
3. Attempting to Modify String (Error Case)
Example 1: Illegal Modification
text = "Python"
text[0] = "J"
Output
TypeError: 'str' object does not support item assignment
Explanation
Strings do not allow direct character modification.
4. Correct Way: Create a New String
Since modification is not allowed, we create a new string.
Example 2: Replace First Character
text = "Python"
new_text = "J" + text[1:]
print(new_text)
Output
Jython
5. How Concatenation Works Internally
Consider:
text = "Hello"
text = text + " World"
Python does NOT change the original string.
Instead:
1. Creates new string "Hello World"
2. Assigns it to text
Old string is discarded.
6. Memory Behavior Demonstration
Example 3: Object Address Change
text = "Python"
print(id(text))
text = text + "3"
print(id(text))
Output shows different memory locations, meaning a new string was created.
7. Why Strings are Immutable?
Immutability provides:
Safety
Strings cannot accidentally change.
Memory Optimization
Same string can be reused.
Example:
a = "Hello"
b = "Hello"
Both may share memory.
Faster Performance
String operations become safer internally.
8. Comparison with Lists
List Modification Allowed
a = [1,2,3]
a[0] = 10
print(a)
Output:
[10,2,3]
String Modification Not Allowed
s = "abc"
s[0] = "x"
Error occurs.
9. Common Beginner Mistakes
Mistake 1
name = "John"
name[1] = "a"
Not allowed.
Mistake 2: Assuming += Modifies String
s = "Hi"
s += "!"
Actually creates a new string.
10. Real-Time Example
Username Correction
username = "user1"
username = [Link]()
print(username)
Output:
USER1
A new string is produced.
11. Practice Exercises
1. Change "Python" to "Jython".
2. Replace last character of string.
3. Convert string to uppercase.
4. Add prefix "Mr." to name.
5. Remove first character using slicing.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 3
String Formatting in Python
In earlier sections, we learned how to combine strings and understood immutability. Now we
learn how to insert values inside strings in a readable format, which is called string
formatting.
String formatting is widely used in:
• Reports
• Billing systems
• Result printing
• Receipts
• Logs and messages
1. What is String Formatting?
String formatting allows us to embed variables or values inside strings.
Instead of writing:
print("Name:", name, "Marks:", marks)
We format neatly:
print(f"Name: {name}, Marks: {marks}")
2. Types of String Formatting in Python
Python mainly supports three styles:
1. Old style formatting using %
2. format() method
3. f-strings (modern method)
We study all three since exam questions may use any.
3. Old Style Formatting (% Operator)
Syntax
"format string" % values
Example 1
name = "Ravi"
marks = 85
print("Name: %s, Marks: %d" % (name, marks))
Output
Name: Ravi, Marks: 85
Common Format Specifiers
Symbol Meaning
%s String
%d Integer
%f Float
Example 2: Float Formatting
price = 99.5
print("Price: %.2f" % price)
Output:
Price: 99.50
4. Using format() Method
More readable and flexible.
Syntax
"string {}".format(value)
Example 3
name = "Asha"
age = 20
print("Name: {}, Age: {}".format(name, age))
Output:
Name: Asha, Age: 20
Example 4: Using Index
print("Age: {1}, Name: {0}".format("Ravi", 21))
Output:
Age: 21, Name: Ravi
Example 5: Named Formatting
print("Name: {n}, Marks: {m}".format(n="Ravi", m=90))
Output:
Name: Ravi, Marks: 90
5. f-Strings (Modern Method – Recommended)
Introduced in Python 3.6.
Syntax
f"string {variable}"
Example 6
name = "John"
marks = 88
print(f"Name: {name}, Marks: {marks}")
Output:
Name: John, Marks: 88
Example 7: Expressions in f-string
a = 5
b = 3
print(f"Sum = {a + b}")
Output:
Sum = 8
Example 8: Decimal Formatting
pi = 3.14159
print(f"Pi value: {pi:.2f}")
Output:
Pi value: 3.14
6. Real-Time Example – Report Card
name = "Ravi"
marks = 87
print(f"Student {name} scored {marks}% marks.")
Output:
Student Ravi scored 87% marks.
7. Alignment Formatting
Example
name = "Ravi"
print(f"|{name:<10}|") # Left aligned
print(f"|{name:>10}|") # Right aligned
print(f"|{name:^10}|") # Center
Output:
|Ravi |
| Ravi|
| Ravi |
8. Common Beginner Mistakes
Missing f in f-string
print("Name: {name}")
Output prints {name} literally.
Correct:
print(f"Name: {name}")
Wrong format specifier
print("%d" % "abc")
Error occurs.
9. Practice Exercises
1. Print name and age using format().
2. Print product price with two decimal places.
3. Display sum of two numbers using f-string.
4. Print centered title using alignment.
5. Print formatted invoice line.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 4
Built-in String Methods and Functions
In previous topics, we learned concatenation, immutability, and formatting. Now we study built-
in string methods, which allow us to analyze and modify strings easily.
String methods are widely used in:
• Input validation
• Text processing
• Search systems
• Data cleaning
• Report generation
1. What are String Methods?
String methods are built-in functions attached to strings.
They are used as:
[Link]()
Example:
name = "python"
print([Link]())
Important Note
Since strings are immutable:
• Methods do not change the original string
• They return a new string
2. Case Conversion Methods
upper() – Convert to Uppercase
text = "python"
print([Link]())
Output:
PYTHON
lower() – Convert to Lowercase
text = "PYTHON"
print([Link]())
Output:
python
title() – Title Case
text = "python programming"
print([Link]())
Output:
Python Programming
capitalize() – First Letter Capital
text = "python language"
print([Link]())
Output:
Python language
3. Search Methods
find() – Find Position
Returns index or -1.
text = "Python Programming"
print([Link]("Pro"))
Output:
count() – Count Occurrences
text = "banana"
print([Link]("a"))
Output:
4. Replace Method
replace()
text = "I like Java"
print([Link]("Java", "Python"))
Output:
I like Python
5. Splitting Strings
split()
Converts string into list.
text = "Python is easy"
print([Link]())
Output:
['Python', 'is', 'easy']
Custom Separator
data = "A,B,C"
print([Link](","))
Output:
['A', 'B', 'C']
6. Joining Strings
join()
Joins list elements into string.
words = ["Python", "is", "fun"]
print(" ".join(words))
Output:
Python is fun
7. Removing Spaces
strip() – Remove spaces both sides
text = " hello "
print([Link]())
lstrip()
Removes left spaces.
rstrip()
Removes right spaces.
8. Checking String Content
isalpha() – Only letters?
print("Python".isalpha())
Output:
True
isdigit() – Only numbers?
print("123".isdigit())
Output:
True
isalnum() – Letters & numbers?
print("Python3".isalnum())
Output:
True
islower() / isupper()
Check case.
9. Starts and Ends Check
startswith()
text = "Python Programming"
print([Link]("Python"))
endswith()
print([Link]("Programming"))
10. Real-Time Example – Input Cleaning
name = input("Enter name: ").strip().title()
print("Hello", name)
Input:
ravi kumar
Output:
Hello Ravi Kumar
11. Common Beginner Mistakes
Mistake 1
[Link]()
print(text)
Original string unchanged.
Correct:
text = [Link]()
Mistake 2
Confusing split and join.
12. Practice Exercises
1. Convert sentence to uppercase.
2. Count vowels in string.
3. Replace word in sentence.
4. Remove extra spaces.
5. Check if input contains only digits.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 5
Slice Operation on Strings
In earlier sections, we learned string methods. Now we study string slicing, which allows us to
extract parts of a string.
Slicing is heavily used in:
• Data extraction
• Username masking
• Date parsing
• Text processing
• File name manipulation
1. What is String Slicing?
Slicing means extracting a portion of a string using index positions.
2. Indexing Recap
Consider:
text = "PYTHON"
Index positions:
Characte
r P Y T H O N
Index 0 1 2 3 4 5
Negative -6 -5 -4 -3 -2 -1
3. Basic Slice Syntax
string[start : end]
• Start index included
• End index excluded
4. Example: Basic Slicing
text = "PYTHON"
print(text[0:3])
Output:
PYT
Explanation: Characters from index 0 to 2.
5. Slice from Beginning
print(text[:4])
Output:
PYTH
Default start is 0.
6. Slice to End
print(text[2:])
Output:
THON
Default end is string length.
7. Negative Index Slicing
print(text[-3:])
Output:
HON
8. Full Copy of String
copy = text[:]
print(copy)
Output:
PYTHON
9. Step Value in Slicing
Syntax:
string[start:end:step]
Step defines jump size.
Example: Skip Characters
print(text[0:6:2])
Output:
PTO
Indexes used: 0,2,4
10. Reverse String Using Slice
Very important.
print(text[::-1])
Output:
NOHTYP
Step = -1 moves backward.
11. Real-Time Examples
Example: Hide Password
pwd = "Python123"
print("*" * len(pwd))
Output:
*********
Example: Mask Phone Number
phone = "9876543210"
masked = phone[:2] + "******" + phone[-2:]
print(masked)
Output:
98******10
Example: Extract Year from Date
date = "25-12-2024"
print(date[-4:])
Output:
2024
12. Common Beginner Errors
Wrong Index
text[10]
IndexError occurs.
Confusing End Position
text[0:3]
Does NOT include index 3.
13. Practice Exercises
1. Extract first 4 characters.
2. Extract last 3 characters.
3. Reverse string.
4. Extract alternate characters.
5. Mask email username.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 6
Comparing Strings in Python
After learning slicing, the next important concept is string comparison. String comparison is
widely used in:
• Login systems
• Input validation
• Searching and sorting data
• Password checks
• Username comparisons
1. What is String Comparison?
String comparison checks whether:
• Two strings are equal
• One string is greater or smaller
• Strings differ
Comparison uses standard operators.
2. Comparison Operators for Strings
Operator Meaning
== Equal to
!= Not equal
< Less than
> Greater than
<= Less or equal
>= Greater or equal
3. Equality Comparison
Example
a = "Python"
b = "Python"
print(a == b)
Output:
True
Example: Not Equal
print("Python" != "Java")
Output:
True
4. How Python Compares Strings
Python compares strings character by character using ASCII/Unicode values.
Comparison occurs from left to right.
Example
print("apple" > "banana")
Output:
False
Explanation:
• Compare first letters:
– 'a' < 'b'
• So result is False.
5. ASCII-Based Comparison
ASCII values determine order.
Character ASCII Value
A 65
Z 90
a 97
z 122
Uppercase letters come before lowercase.
Example
print("Apple" > "apple")
Output:
False
Because:
'A' < 'a'
6. Case-Sensitive Comparison
Comparison is case-sensitive.
print("Python" == "python")
Output:
False
7. Case-Insensitive Comparison
Convert both strings to same case.
a = "Python"
b = "python"
print([Link]() == [Link]())
Output:
True
8. Real-Time Example – Login System
stored_user = "admin"
user = input("Enter username: ")
if [Link]() == stored_user:
print("Login allowed")
else:
print("Invalid user")
9. Lexicographical Order Example
print("cat" < "dog")
Output:
True
Because 'c' comes before 'd'.
10. Sorting Strings
names = ["John", "Alice", "Bob"]
[Link]()
print(names)
Output:
['Alice', 'Bob', 'John']
Sorting uses string comparison rules.
11. Common Beginner Mistakes
Mistake 1: Case mismatch
"Admin" == "admin"
False.
Mistake 2: Comparing numbers as strings
"10" > "2"
Output:
False
Because character comparison occurs.
12. Practice Exercises
1. Compare two user inputs.
2. Check if two words are same ignoring case.
3. Find larger word between two.
4. Sort list of names.
5. Compare passwords safely.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 7
Iterating Through Strings
After learning string comparison, the next important concept is iterating through strings.
Iteration means accessing each character one by one.
This is widely used in:
• Password validation
• Counting vowels
• Searching characters
• Text analysis
• Data cleaning
1. What is String Iteration?
Since a string is a sequence of characters, we can use loops to access each character.
Example string:
text = "Python"
2. Iteration Using for Loop (Recommended
Method)
Example 1: Print Each Character
text = "Python"
for ch in text:
print(ch)
Output
P
y
t
h
o
n
3. Iteration Using Index
We can also use range() and len().
Example 2:
text = "Python"
for i in range(len(text)):
print(text[i])
Output:
P
y
t
h
o
n
4. Iteration with Position Information
Example 3:
text = "Python"
for i in range(len(text)):
print("Index:", i, "Character:", text[i])
Output:
Index: 0 Character: P
Index: 1 Character: y
Index: 2 Character: t
Index: 3 Character: h
Index: 4 Character: o
Index: 5 Character: n
5. Real-Time Example – Count Vowels
text = "Python Programming"
count = 0
for ch in [Link]():
if ch in "aeiou":
count += 1
print("Number of vowels:", count)
Output:
Number of vowels: 4
6. Example – Count Digits in String
text = "Python3Version9"
digits = 0
for ch in text:
if [Link]():
digits += 1
print("Digits count:", digits)
Output:
Digits count: 2
7. Example – Reverse Using Loop
text = "Python"
reverse = ""
for ch in text:
reverse = ch + reverse
print(reverse)
Output:
nohtyP
8. Using while Loop
text = "Python"
i = 0
while i < len(text):
print(text[i])
i += 1
9. Breaking Loop Early
text = "Python"
for ch in text:
if ch == "h":
break
print(ch)
Output:
P
y
t
10. Skipping Characters
text = "Python"
for ch in text:
if ch == "o":
continue
print(ch)
Output:
P
y
t
h
n
11. Common Beginner Mistakes
Mistake 1: Modifying character directly
for ch in text:
ch = [Link]()
Does not modify original string.
Mistake 2: Forgetting .lower() when checking vowels
Case mismatch occurs.
12. Practice Exercises
1. Count uppercase letters.
2. Count consonants.
3. Remove digits from string.
4. Print characters at even positions.
5. Check if string contains special characters.
UNIT IV – STRINGS AND FILE HANDLING
STRINGS – Part 8
String Module and Regular Expressions
In previous sections, we learned basic string operations and methods. Now we move to slightly
advanced tools used for text processing and pattern matching.
This section covers:
1. String Module
2. Regular Expressions (re module)
Both are important for:
• Input validation
• Data cleaning
• Pattern matching
• Searching complex text
• Password validation
• Email checking
PART 1 – STRING MODULE
Python provides a built-in module called string which contains useful constants.
To use it:
import string
1. Important String Module Constants
1.1 string.ascii_letters
Contains all uppercase and lowercase letters.
import string
print(string.ascii_letters)
Output:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
1.2 string.ascii_lowercase
print(string.ascii_lowercase)
Output:
abcdefghijklmnopqrstuvwxyz
1.3 string.ascii_uppercase
print(string.ascii_uppercase)
1.4 [Link]
print([Link])
Output:
0123456789
1.5 [Link]
print([Link])
Output:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
1.6 [Link]
print([Link])
Shows space, tab, newline characters.
Real-Time Example – Check Password Strength
import string
password = "Python@123"
has_letter = False
has_digit = False
has_symbol = False
for ch in password:
if ch in string.ascii_letters:
has_letter = True
elif ch in [Link]:
has_digit = True
elif ch in [Link]:
has_symbol = True
if has_letter and has_digit and has_symbol:
print("Strong Password")
else:
print("Weak Password")
PART 2 – REGULAR EXPRESSIONS (re Module)
Regular Expressions (RegEx) are used to:
• Search patterns in text
• Validate formats
• Extract data
To use:
import re
1. Basic Pattern Searching
1.1 [Link]()
Searches pattern anywhere in string.
import re
text = "Python Programming"
result = [Link]("Python", text)
if result:
print("Found")
else:
print("Not Found")
Output:
Found
1.2 [Link]()
Finds all matches.
text = "abc 123 def 456"
numbers = [Link](r"\d+", text)
print(numbers)
Output:
['123', '456']
2. Common Pattern Symbols
Symbol Meaning
\d Digit
\D Non-digit
\w Word character
\W Non-word character
. Any character
^ Start of string
$ End of string
3. Validate Email Example
import re
email = "test@[Link]"
pattern = r"^\w+@\w+\.\w+$"
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")
4. Replace Using Regular Expression
import re
text = "My number is 12345"
new_text = [Link](r"\d+", "XXXXX", text)
print(new_text)
Output:
My number is XXXXX
5. Split Using Regular Expression
import re
text = "apple,banana;orange"
words = [Link](r"[;,]", text)
print(words)
Output:
['apple', 'banana', 'orange']
Common Beginner Mistakes
1. Forgetting import re
2. Using wrong pattern symbols
3. Missing r before pattern string
Correct:
r"\d+"
Practice Exercises
1. Extract all digits from string.
2. Validate phone number.
3. Replace multiple spaces with single space.
4. Check if string starts with capital letter.
5. Extract all words from sentence.
UNIT IV – STRINGS AND FILE HANDLING
FILE HANDLING – Part 1
File Path and Types of Files
After completing the Strings section, we now move to File Handling, which allows Python
programs to store and retrieve data permanently.
File handling is essential in real-world applications such as:
• Data logging
• Report generation
• Database backups
• Reading configuration files
• Processing datasets
1. What is File Handling?
File handling refers to the process of:
• Creating files
• Opening files
• Reading data from files
• Writing data to files
• Updating files
• Closing files
Files allow data to be stored permanently on disk instead of temporary program memory.
2. Why File Handling is Needed
Without files:
• Data disappears when the program ends.
Example:
marks = 90
When program stops → value disappears.
With files:
[Link]
---------
90
Data remains stored even after program stops.
3. What is a File Path?
A file path tells Python where a file is located.
Example paths:
Windows
C:\Users\Student\[Link]
Linux / Mac
/home/student/[Link]
Example Using File Path
file = open("[Link]")
Python searches for [Link] in the current working directory.
Absolute vs Relative Path
Path Type Description Example
Absolute Path Full location C:\Users\Student\
[Link]
Relative Path Current folder [Link]
Example Absolute Path
file = open("C:\\Users\\Student\\[Link]")
Note: Double \\ is required in Windows.
4. Types of Files
Files are mainly classified into two types.
1. Text Files
Text files store readable characters.
Examples:
.txt
.csv
.py
.json
.xml
Example content of text file:
Name: Ravi
Age: 20
Marks: 85
Text files are easy for humans to read.
Example Reading Text File
file = open("[Link]", "r")
content = [Link]()
print(content)
2. Binary Files
Binary files store data in binary format (0s and 1s).
Examples:
.jpg
.png
.mp3
.mp4
.exe
.pdf
Binary files cannot be read directly as text.
Example Binary File
Opening image file:
file = open("[Link]", "rb")
b means binary mode.
Text vs Binary Files
Feature Text File Binary File
Human readable Yes No
Examples txt, csv jpg, mp3
Mode r, w rb, wb
5. File Modes Overview
When opening a file, we specify the mode.
Mode Meaning
r Read
w Write
a Append
Mode Meaning
rb Read binary
wb Write binary
Example:
file = open("[Link]", "r")
6. Real-Time Example – Student Record File
Suppose we store records in a file:
[Link]
Ravi,85
Anita,90
Kumar,78
Python program can read and process these records.
Example Program
file = open("[Link]", "r")
data = [Link]()
print(data)
[Link]()
Output Example
Ravi,85
Anita,90
Kumar,78
7. Important Rule
Always close files after using them.
[Link]()
This releases system resources.
8. Common Beginner Mistakes
File not found
open("[Link]")
Error:
FileNotFoundError
Because file does not exist.
Forgetting to close file
This can cause memory issues.
9. Practice Exercises
1. Create a file called [Link].
2. Write three names into the file.
3. Read file content and display.
4. Open a binary file example.
5. Print file path used in program.
UNIT IV – STRINGS AND FILE HANDLING
FILE HANDLING – Part 2
Opening and Closing Files in Python
In the previous section, we learned about file paths and types of files. Now we study how to
open and close files properly, which is the first step in file processing.
1. Opening a File
Python provides the built-in open() function to open a file.
Syntax
file_object = open("filename", "mode")
Where:
Parameter Meaning
filename Name or path of the file
mode Operation to perform on file
2. File Opening Modes
Mode Description
r Read file
w Write file (overwrites file)
a Append to file
x Create new file
rb Read binary file
wb Write binary file
3. Read Mode (r)
Used to read existing files.
Example
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Example File Content
Python
Java
C++
Output
Python
Java
C++
Important Rule
If file does not exist in r mode:
Error occurs
FileNotFoundError
4. Write Mode (w)
Used to write data into file.
If file exists → content will be erased.
Example
file = open("[Link]", "w")
[Link]("Python Programming")
[Link]()
File content becomes:
Python Programming
5. Append Mode (a)
Append mode adds data to the end of file.
Existing data is preserved.
Example
file = open("[Link]", "a")
[Link]("\nMachine Learning")
[Link]()
File content:
Python Programming
Machine Learning
6. Create Mode (x)
Creates a new file only.
If file already exists → error occurs.
Example
file = open("[Link]", "x")
[Link]()
7. Binary Mode Example
Binary files store non-text data.
Example
file = open("[Link]", "rb")
data = [Link]()
[Link]()
8. Closing a File
After using a file, we must close it.
Syntax
[Link]()
Closing file:
• releases memory
• saves changes
• prevents data corruption
Example
file = open("[Link]", "r")
print([Link]())
[Link]()
9. Safer Method – Using with open()
Python provides a safer way.
Syntax
with open("[Link]", "mode") as file:
statements
Advantages:
• File closes automatically
• Prevents memory leaks
• Recommended method
Example
with open("[Link]", "r") as file:
content = [Link]()
print(content)
No need for [Link]().
10. Real-Time Example – Log File
with open("[Link]", "a") as file:
[Link]("User login successful\n")
This adds logs continuously.
11. Common Beginner Mistakes
Forgetting close()
file = open("[Link]")
Should close file.
Wrong file path
open("C:[Link]")
Correct:
open("C:\\[Link]")
Using write in read mode
file = open("[Link]","r")
[Link]("Hello")
Error occurs.
12. Practice Exercises
1. Create a file called [Link].
2. Write three lines into file.
3. Append another line.
4. Read the file content.
5. Use with open() to read file.
UNIT IV – STRINGS AND FILE HANDLING
FILE HANDLING – Part 3
Reading and Writing Files in Python
After learning how to open and close files, the next step is understanding how to read data
from files and write data to files.
This is a fundamental skill used in:
• Data processing systems
• Log file analysis
• Report generation
• Configuration file reading
• Storing user records
1. Reading Data from Files
Python provides several methods to read file content.
Method Description
read() Reads entire file
Method Description
readline() Reads one line
readlines() Reads all lines into a list
2. Using read() Method
The read() method reads the entire file content as a string.
Example File ([Link])
Python
Java
C++
Machine Learning
Example Program
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Output
Python
Java
C++
Machine Learning
3. Reading Specific Number of Characters
read(n) reads only n characters.
Example
with open("[Link]", "r") as file:
content = [Link](6)
print(content)
Output
Python
4. Using readline()
Reads one line at a time.
Example
with open("[Link]", "r") as file:
line = [Link]()
print(line)
Output
Python
Reading Multiple Lines
with open("[Link]", "r") as file:
print([Link]())
print([Link]())
Output
Python
Java
5. Using readlines()
Reads all lines and stores them in a list.
Example
with open("[Link]", "r") as file:
lines = [Link]()
print(lines)
Output
['Python\n', 'Java\n', 'C++\n', 'Machine Learning']
6. Iterating Through File
Best method for large files.
Example
with open("[Link]", "r") as file:
for line in file:
print([Link]())
Output
Python
Java
C++
Machine Learning
7. Writing to Files
Writing is done using the write() method.
Syntax
[Link]("text")
Example
with open("[Link]", "w") as file:
[Link]("Python is easy to learn")
File content becomes
Python is easy to learn
Important Rule
Mode "w" overwrites existing data.
8. Writing Multiple Lines
with open("[Link]", "w") as file:
[Link]("Python\n")
[Link]("Java\n")
[Link]("C++\n")
File content
Python
Java
C++
9. Using writelines()
Writes a list of strings.
Example
lines = ["Python\n", "AI\n", "Data Science\n"]
with open("[Link]", "w") as file:
[Link](lines)
10. Appending Data
Append mode adds content without deleting old data.
Example
with open("[Link]", "a") as file:
[Link]("\nMachine Learning")
File content
Python
Java
C++
Machine Learning
11. Real-Time Example – Student Marks File
File ([Link])
Ravi 85
Anita 92
Kumar 78
Python Program
with open("[Link]", "r") as file:
for line in file:
name, marks = [Link]()
print("Student:", name, "Marks:", marks)
Output
Student: Ravi Marks: 85
Student: Anita Marks: 92
Student: Kumar Marks: 78
12. Common Beginner Mistakes
Forgetting newline
[Link]("Python")
[Link]("Java")
Output
PythonJava
Correct
[Link]("Python\n")
Writing list directly
[Link](["Python","Java"])
Error occurs.
Correct
[Link]()
13. Practice Exercises
1. Create a file called [Link].
2. Write 5 student names into the file.
3. Read and display all names.
4. Append a new name to the file.
5. Count number of lines in the file.
UNIT IV – STRINGS AND FILE HANDLING
FILE HANDLING – Part 4
File Positions in Python
When Python reads or writes a file, it uses an internal pointer called the file cursor (file pointer).
Understanding file position is important for:
• Random access reading
• Re-reading file content
• Skipping parts of files
• Processing large files efficiently
1. What is File Position?
When a file is opened, Python places a cursor at the beginning of the file.
Example file:
Python
Java
C++
Cursor initially points here:
|Python
Java
C++
After reading characters, the cursor moves forward.
2. tell() Function
tell() returns the current position of the file pointer.
Example
with open("[Link]", "r") as file:
print([Link]())
Output
0
Cursor is at position 0 (start of file).
Example After Reading
with open("[Link]", "r") as file:
[Link](5)
print([Link]())
Output
5
Cursor moved 5 characters forward.
3. seek() Function
seek() moves the file pointer to a specific position.
Syntax
[Link](position)
Example
with open("[Link]", "r") as file:
[Link](3)
print([Link]())
Example File
Python Programming
Output
hon Programming
Cursor moved to position 3.
4. Reset File Pointer to Beginning
Very common operation.
[Link](0)
Example
with open("[Link]", "r") as file:
print([Link](6))
[Link](0)
print([Link](6))
Output
Python
Python
The pointer returned to the beginning.
5. Real-Time Example – Log Analyzer
Suppose a program reads a file and needs to reprocess it.
with open("[Link]", "r") as file:
print([Link](10))
[Link](0)
print([Link](10))
6. Example Showing Pointer Movement
with open("[Link]", "r") as file:
print("Initial position:", [Link]())
[Link](4)
print("After reading 4 chars:", [Link]())
[Link](2)
print("After seek:", [Link]())
Possible Output
Initial position: 0
After reading 4 chars: 4
After seek: 2
7. Practical Example – Re-reading File
with open("[Link]", "r") as file:
first_read = [Link](5)
print(first_read)
[Link](0)
second_read = [Link](5)
print(second_read)
Output
Python
Python
8. Important Notes
Function Purpose
tell() Shows current cursor position
seek() Moves cursor position
9. Common Beginner Mistakes
Forgetting pointer position
Example:
[Link]()
[Link]()
Second read returns nothing.
Because pointer reached end of file.
Solution
Reset pointer:
[Link](0)
10. Practice Exercises
1. Open a file and print cursor position.
2. Read first 10 characters and print cursor position.
3. Reset cursor and read again.
4. Move cursor to position 5 using seek().
5. Display remaining content.
UNIT IV – STRINGS AND FILE HANDLING
FILE HANDLING – Part 5 (Final Topic)
Renaming and Deleting Files in Python
After learning how to open, read, write, and control file positions, the final file handling
concept is managing files.
Python allows programs to rename and delete files using the os module.
These operations are commonly used in:
• Log file management
• Data backup systems
• File organization tools
• Cleaning temporary files
• Report generation systems
1. The os Module
The os module provides functions to interact with the operating system.
To use it:
import os
2. Renaming Files
Python uses the function:
[Link](old_name, new_name)
This changes the file name.
Example – Rename File
Suppose we have a file:
[Link]
We want to rename it to:
[Link]
Program
import os
[Link]("[Link]", "[Link]")
print("File renamed successfully")
Result
[Link] → [Link]
3. Renaming File with Path
You can rename files using full file path.
Example:
import os
[Link]("C:\\data\\[Link]", "C:\\data\\[Link]")
4. Deleting Files
Python deletes files using:
[Link](filename)
Example – Delete File
import os
[Link]("[Link]")
print("File deleted successfully")
Important Note
Once deleted, the file cannot be recovered easily.
So programs should check before deleting.
5. Safe Deletion Using File Check
Use [Link]().
Example
import os
file_name = "[Link]"
if [Link](file_name):
[Link](file_name)
print("File deleted")
else:
print("File does not exist")
Output Example
File deleted
6. Real-Time Example – Log File Cleanup
Suppose a system deletes old log files automatically.
Program
import os
log_file = "system_log.txt"
if [Link](log_file):
[Link](log_file)
print("Old log removed")
else:
print("Log file not found")
7. Real-Time Example – File Version Update
A report generator renames files daily.
[Link] → report_old.txt
Program
import os
if [Link]("[Link]"):
[Link]("[Link]", "report_old.txt")
8. Common Beginner Mistakes
Forgetting to import os
[Link]("[Link]")
Error:
NameError: os not defined
Correct:
import os
Deleting non-existing file
[Link]("[Link]")
Error:
FileNotFoundError
Use [Link]().
9. Important File Management Functions
Function Purpose
[Link]() Rename file
[Link]() Delete file
[Link]() Check file existence
10. Practice Exercises
1. Create a file called [Link].
2. Rename it to [Link].
3. Check whether [Link] exists.
4. Delete the file.
5. Display message if file does not exist.
UNIT IV – Practice Problems
1. Email Log Analyzer System
Problem
A company stores login emails in a file [Link].
Example file:
ravi@[Link]
asha@[Link]
john@[Link]
ravi@[Link]
Write a Python program to:
1. Read emails from file.
2. Extract username and domain using string operations.
3. Count unique users per domain.
4. Display result using formatted output.
Solution
emails = open("[Link]","r").read().splitlines()
domain_users = {}
for email in emails:
username, domain = [Link]("@")
if domain not in domain_users:
domain_users[domain] = set()
domain_users[domain].add(username)
for domain, users in domain_users.items():
print(f"{domain} → {len(users)} unique users")
2. Password Strength Validator
Problem
Validate passwords stored in a file [Link].
Rules:
• Must contain uppercase, lowercase, digit, and symbol
• Minimum length 8
• Use string module and regex
Solution
import re
import string
with open("[Link]","r") as file:
passwords = [Link]()
pattern = r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?
=.*['+[Link]+']).{8,}$'
for p in passwords:
p = [Link]()
if [Link](pattern,p):
print(f"{p} : Strong")
else:
print(f"{p} : Weak")
3. Text File Word Frequency Analyzer
Problem
Analyze a file [Link] and print the top 5 most frequent words.
Requirements:
• Remove punctuation using string module
• Use iteration and string methods
• Use file reading
Solution
import string
with open("[Link]","r") as file:
text = [Link]().lower()
for p in [Link]:
text = [Link](p,"")
words = [Link]()
freq = {}
for w in words:
freq[w] = [Link](w,0) + 1
sorted_words = sorted([Link](), key=lambda x:x[1], reverse=True)
print(sorted_words[:5])
4. File Data Masking System
Problem
A file [Link] contains:
Ravi 9876543210
Asha 8765432109
Create [Link] where phone numbers become:
Ravi 98******10
Use slice operations.
Solution
with open("[Link]","r") as file:
lines = [Link]()
out = open("[Link]","w")
for line in lines:
name, phone = [Link]()
masked = phone[:2] + "*"*6 + phone[-2:]
[Link](f"{name} {masked}\n")
[Link]()
5. Palindrome Sentence Detector
Problem
From a file [Link], detect which sentences are palindromes ignoring spaces and case.
Use string methods and slicing.
Solution
with open("[Link]","r") as file:
sentences = [Link]()
for s in sentences:
clean = [Link](" ","").lower().strip()
if clean == clean[::-1]:
print(f"Palindrome → {[Link]()}")
6. Log File Date Extractor (Regex)
Problem
Extract dates from a log file.
Example line:
Error occurred on 12-05-2024
Use regular expressions to extract dates.
Solution
import re
pattern = r"\d{2}-\d{2}-\d{4}"
with open("[Link]","r") as file:
data = [Link]()
dates = [Link](pattern,data)
print("Dates found:", dates)
7. Smart File Reader Using File Positions
Problem
Read first 10 characters from a file, reset pointer, then read again.
Use tell() and seek().
Solution
file = open("[Link]","r")
print([Link](10))
print("Pointer position:",[Link]())
[Link](0)
print([Link](10))
[Link]()
8. Username Generator System
Problem
From file [Link]:
Ravi Kumar
John Smith
Generate usernames:
rkumar
jsmith
Use:
• slicing
• concatenation
• string methods
Solution
with open("[Link]","r") as file:
for line in file:
first,last = [Link]().split()
username = first[0] + last
print(username)
9. File Backup and Rename System
Problem
Before editing a file, create backup.
Example:
[Link] → data_backup.txt
Use file rename operation.
Solution
import os
if [Link]("[Link]"):
[Link]("[Link]","data_backup.txt")
print("Backup created")
10. Automatic File Cleaner
Problem
Delete all temporary files with .tmp extension from a folder.
Use regex + os module.
Solution
import os
import re
files = [Link]()
for f in files:
if [Link](r"\.tmp$",f):
[Link](f)
print(f"{f} deleted")