<h2>14.1 Introduction to File Handling</h2>
<p>
File handling is used to create, read, write, update, and manage files
using Python. It is useful when a program needs to store information
permanently instead of keeping it only in memory.
</p>
<p>
Python provides the built-in <code>open()</code> function for working
with files.
</p>
<pre><code>file = open("example.txt", "r")
print(file)
file.close()</code></pre>
<h2>14.2 Opening a File</h2>
<p>
The <code>open()</code> function is used to open a file.
It commonly accepts a file name and a mode.
</p>
<pre><code>file = open("example.txt", "r")
print("File opened successfully")
file.close()</code></pre>
<h2>14.3 File Modes</h2>
<p>
Python provides different modes for different file operations.
</p>
<table>
<thead>
<tr>
<th>Mode</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>r</code></td>
<td>Read a file</td>
</tr>
<tr>
<td><code>w</code></td>
<td>Write to a file</td>
</tr>
<tr>
<td><code>a</code></td>
<td>Append data to a file</td>
</tr>
<tr>
<td><code>x</code></td>
<td>Create a new file</td>
</tr>
<tr>
<td><code>r+</code></td>
<td>Read and write</td>
</tr>
<tr>
<td><code>w+</code></td>
<td>Write and read</td>
</tr>
<tr>
<td><code>a+</code></td>
<td>Append and read</td>
</tr>
</tbody>
</table>
<h2>14.4 Reading a File</h2>
<p>
The <code>read()</code> method reads the contents of a file.
</p>
<pre><code>file = open("example.txt", "r")
content = file.read()
print(content)
file.close()</code></pre>
<h2>14.5 Reading a Specific Number of Characters</h2>
<p>
You can provide a number to <code>read()</code> to read a specific
number of characters.
</p>
<pre><code>file = open("example.txt", "r")
content = file.read(10)
print(content)
file.close()</code></pre>
<h2>14.6 Reading One Line</h2>
<p>
The <code>readline()</code> method reads one line from a file.
</p>
<pre><code>file = open("example.txt", "r")
line = file.readline()
print(line)
file.close()</code></pre>
<h2>14.7 Reading Multiple Lines</h2>
<p>
The <code>readlines()</code> method returns the lines of a file as a
list.
</p>
<pre><code>file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()</code></pre>
<h2>14.8 Reading a File Using a Loop</h2>
<p>
A file can also be processed one line at a time using a
<code>for</code> loop.
</p>
<pre><code>file = open("example.txt", "r")
for line in file:
print(line)
file.close()</code></pre>
<h2>14.9 Writing to a File</h2>
<p>
The <code>w</code> mode is used to write data to a file. If the file
already exists, its previous contents can be replaced.
</p>
<pre><code>file = open("example.txt", "w")
file.write("Hello from Python!")
file.close()</code></pre>
<h2>14.10 Writing Multiple Lines</h2>
<pre><code>file = open("students.txt", "w")
file.write("Aman\n")
file.write("Ravi\n")
file.write("Neha\n")
file.close()</code></pre>
<h2>14.11 Writing Multiple Lines with writelines()</h2>
<p>
The <code>writelines()</code> method can write multiple strings to
a file.
</p>
<pre><code>students = [
"Aman\n",
"Ravi\n",
"Neha\n"
]
file = open("students.txt", "w")
file.writelines(students)
file.close()</code></pre>
<h2>14.12 Appending Data to a File</h2>
<p>
The <code>a</code> mode adds new content to the end of an existing
file without replacing its previous contents.
</p>
<pre><code>file = open("students.txt", "a")
file.write("Rahul\n")
file.close()</code></pre>
<h2>14.13 Creating a New File</h2>
<p>
The <code>x</code> mode can be used to create a new file.
If the file already exists, Python raises an error.
</p>
<pre><code>file = open("newfile.txt", "x")
file.write("This is a new file.")
file.close()</code></pre>
<h2>14.14 Using with to Open a File</h2>
<p>
The <code>with</code> statement is a convenient way to work with files.
Python automatically closes the file when the block finishes.
</p>
<pre><code>with open("example.txt", "r") as file:
content = file.read()
print(content)</code></pre>
<h2>14.15 Why Use with?</h2>
<p>
Using <code>with</code> makes file-handling code cleaner and helps ensure
that the file is properly closed after use.
</p>
<pre><code>with open("example.txt", "w") as file:
file.write("Python File Handling")</code></pre>
<h2>14.16 Checking Whether a File Exists</h2>
<p>
The <code>os.path.exists()</code> function can be used to check whether
a file or directory exists.
</p>
<pre><code>import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File does not exist")</code></pre>
<h2>14.17 Deleting a File</h2>
<p>
The <code>os.remove()</code> function can be used to delete a file.
</p>
<pre><code>import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted")
else:
print("File not found")</code></pre>
<h2>14.18 Creating a Directory</h2>
<p>
The <code>os.mkdir()</code> function can create a new directory.
</p>
<pre><code>import os
if not os.path.exists("documents"):
os.mkdir("documents")
print("Directory ready")</code></pre>
<h2>14.19 Listing Files and Folders</h2>
<p>
The <code>os.listdir()</code> function returns the files and folders
inside a specified directory.
</p>
<pre><code>import os
items = os.listdir(".")
for item in items:
print(item)</code></pre>
<h2>14.20 Getting the Current Working Directory</h2>
<pre><code>import os
location = os.getcwd()
print("Current directory:", location)</code></pre>
<h2>14.21 Changing the Current Directory</h2>
<p>
The <code>os.chdir()</code> function can change the current working
directory.
</p>
<pre><code>import os
os.chdir("documents")
print(os.getcwd())</code></pre>
<h2>14.22 Reading Text from a File</h2>
<p>
Text files can be read using normal file operations.
</p>
<pre><code>with open("message.txt", "r") as file:
message = file.read()
print(message)</code></pre>
<h2>14.23 Writing Student Information</h2>
<pre><code>name = "Aman"
age = 16
marks = 88
with open("student.txt", "w") as file:
file.write("Name: " + name + "\n")
file.write("Age: " + str(age) + "\n")
file.write("Marks: " + str(marks) + "\n")</code></pre>
<h2>14.24 Reading Student Information</h2>
<pre><code>with open("student.txt", "r") as file:
data = file.read()
print(data)</code></pre>
<h2>14.25 Using f-Strings with Files</h2>
<p>
f-strings provide a convenient way to write formatted information
into a file.
</p>
<pre><code>name = "Aman"
marks = 92
with open("result.txt", "w") as file:
file.write(f"Student: {name}\n")
file.write(f"Marks: {marks}\n")</code></pre>
<h2>14.26 File Position with tell()</h2>
<p>
The <code>tell()</code> method returns the current position of the
file pointer.
</p>
<pre><code>with open("example.txt", "r") as file:
print(file.tell())
file.read(5)
print(file.tell())</code></pre>
<h2>14.27 Moving the File Pointer with seek()</h2>
<p>
The <code>seek()</code> method moves the file pointer to a specified
position.
</p>
<pre><code>with open("example.txt", "r") as file:
file.seek(0)
content = file.read()
print(content)</code></pre>
<h2>14.28 Reading Binary Files</h2>
<p>
Files such as images and some other non-text files can be opened in
binary mode using <code>b</code>.
</p>
<pre><code>with open("image.jpg", "rb") as file:
data = file.read()
print("Binary data loaded")</code></pre>
<h2>14.29 Writing Binary Data</h2>
<pre><code>with open("copy.jpg", "wb") as output:
output.write(data)</code></pre>
<h2>14.30 Handling File Errors</h2>
<p>
File operations can fail for different reasons. For example, a file
may not exist. Python provides <code>try</code> and
<code>except</code> for handling such errors.
</p>
<pre><code>try:
with open("missing.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file was not found.")</code></pre>
<h2>14.31 Handling Permission Errors</h2>
<pre><code>try:
with open("example.txt", "r") as file:
content = file.read()
except PermissionError:
print("Permission denied.")</code></pre>
<h2>14.32 Reading Lines into a List</h2>
<pre><code>with open("students.txt", "r") as file:
students = file.readlines()
print(students)</code></pre>
<h2>14.33 Removing Newline Characters</h2>
<p>
The <code>strip()</code> method can remove unnecessary whitespace and
newline characters from each line.
</p>
<pre><code>with open("students.txt", "r") as file:
for line in file:
print(line.strip())</code></pre>
<h2>14.34 Counting Lines in a File</h2>
<pre><code>count = 0
with open("students.txt", "r") as file:
for line in file:
count += 1
print("Number of lines:", count)</code></pre>
<h2>14.35 Counting Words in a File</h2>
<pre><code>with open("example.txt", "r") as file:
content = file.read()
words = content.split()
print("Number of words:", len(words))</code></pre>
<h2>14.36 Counting Characters in a File</h2>
<pre><code>with open("example.txt", "r") as file:
content = file.read()
print("Characters:", len(content))</code></pre>
<h2>14.37 Searching Text in a File</h2>
<p>
The <code>in</code> operator can be used to check whether particular
text exists in a file.
</p>
<pre><code>with open("example.txt", "r") as file:
content = file.read()
if "Python" in content:
print("Python was found")
else:
print("Python was not found")</code></pre>
<h2>14.38 Replacing Text in a File</h2>
<p>
You can read a file, modify its contents, and then write the updated
content back to the file.
</p>
<pre><code>with open("example.txt", "r") as file:
content = file.read()
content = content.replace("Python", "Programming")
with open("example.txt", "w") as file:
file.write(content)</code></pre>
<h2>14.39 Copying a Text File</h2>
<pre><code>with open("source.txt", "r") as source:
content = source.read()
with open("backup.txt", "w") as backup:
backup.write(content)
print("File copied successfully")</code></pre>
<h2>14.40 Appending Student Records</h2>
<pre><code>name = input("Enter student name: ")
marks = input("Enter marks: ")
with open("students.txt", "a") as file:
file.write(f"{name} - {marks}\n")
print("Student record saved")</code></pre>
<h2>14.41 Simple Notes Application</h2>
<p>
The following example creates a small text-based notes application.
</p>
<pre><code>note = input("Enter your note: ")
with open("notes.txt", "a") as file:
file.write(note + "\n")
print("Note saved successfully")</code></pre>
<h2>14.42 Reading Notes</h2>
<pre><code>with open("notes.txt", "r") as file:
notes = file.read()
print("Your Notes:")
print(notes)</code></pre>
<h2>14.43 Student Result File</h2>
<pre><code>name = "Aman"
marks = [78, 85, 92, 88, 90]
total = sum(marks)
average = total / len(marks)
with open("result.txt", "w") as file:
file.write(f"Student: {name}\n")
file.write(f"Marks: {marks}\n")
file.write(f"Total: {total}\n")
file.write(f"Average: {average}\n")</code></pre>
<h2>14.44 File Handling with a Function</h2>
<p>
File operations can also be placed inside functions to make programs
more organized and reusable.
</p>
<pre><code>def save_message(message):
with open("message.txt", "w") as file:
file.write(message)
save_message("Welcome to Python File Handling!")</code></pre>
<h2>14.45 Reading a File Using a Function</h2>
<pre><code>def read_message():
with open("message.txt", "r") as file:
return file.read()
message = read_message()
print(message)</code></pre>
<h2>14.46 File Handling with JSON</h2>
<p>
Python's <code>json</code> module can be used to store structured
data in a JSON file.
</p>
<pre><code>import json
student = {
"name": "Aman",
"age": 16,
"marks": 88
}
with open("student.json", "w") as file:
json.dump(student, file, indent=4)</code></pre>
<h2>14.47 Reading JSON from a File</h2>
<pre><code>import json
with open("student.json", "r") as file:
student = json.load(file)
print(student["name"])
print(student["marks"])</code></pre>
<h2>14.48 File Handling Best Practices</h2>
<ul>
<li>Use <code>with open()</code> whenever practical.</li>
<li>Choose the correct file mode.</li>
<li>Handle missing files with appropriate exceptions.</li>
<li>Use clear and meaningful file names.</li>
<li>Avoid overwriting important files accidentally.</li>
<li>Close files when they are opened without a context manager.</li>
<li>Validate data before saving it.</li>
</ul>
<h2>14.49 Common File Handling Methods</h2>
<table>
<thead>
<tr>
<th>Method</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>read()</code></td>
<td>Reads file contents</td>
</tr>
<tr>
<td><code>readline()</code></td>
<td>Reads one line</td>
</tr>
<tr>
<td><code>readlines()</code></td>
<td>Reads lines into a list</td>
</tr>
<tr>
<td><code>write()</code></td>
<td>Writes text to a file</td>
</tr>
<tr>
<td><code>writelines()</code></td>
<td>Writes multiple strings</td>
</tr>
<tr>
<td><code>seek()</code></td>
<td>Moves the file pointer</td>
</tr>
<tr>
<td><code>tell()</code></td>
<td>Returns the current file position</td>
</tr>
<tr>
<td><code>close()</code></td>
<td>Closes the file</td>
</tr>
</tbody>
</table>
<h2>14.50 File Modes Quick Revision</h2>
<table>
<thead>
<tr>
<th>Mode</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>r</code></td>
<td>Read existing file</td>
</tr>
<tr>
<td><code>w</code></td>
<td>Write and replace existing contents</td>
</tr>
<tr>
<td><code>a</code></td>
<td>Add data at the end</td>
</tr>
<tr>
<td><code>x</code></td>
<td>Create a new file</td>
</tr>
<tr>
<td><code>b</code></td>
<td>Binary mode</td>
</tr>
<tr>
<td><code>+</code></td>
<td>Enable both reading and writing</td>
</tr>
</tbody>
</table>
<h2>14.51 Chapter Summary</h2>
<p>
In this chapter, you learned how Python can work with files for
permanent data storage. You learned how to create, read, write,
append, update, search, and manage files.
</p>
<ul>
<li>Opening files</li>
<li>File modes</li>
<li>Reading files</li>
<li>Writing files</li>
<li>Appending data</li>
<li>Creating files</li>
<li>Using the <code>with</code> statement</li>
<li>Checking and deleting files</li>
<li>Working with directories</li>
<li>Using <code>seek()</code> and <code>tell()</code></li>
<li>Handling file errors</li>
<li>Working with JSON files</li>
</ul>
<h2>14.52 Quick Revision Questions</h2>
<ol>
<li>What is file handling?</li>
<li>Which function is used to open a file in Python?</li>
<li>What is the purpose of the <code>r</code> mode?</li>
<li>What is the difference between <code>w</code> and <code>a</code>?</li>
<li>What does <code>read()</code> do?</li>
<li>What is the purpose of <code>readline()</code>?</li>
<li>Why is the <code>with</code> statement useful?</li>
<li>How can you delete a file?</li>
<li>What does <code>seek()</code> do?</li>
<li>What is JSON file handling?</li>
</ol>
<h2>14.53 Practice Exercises</h2>
<ol>
<li>Create a text file and write five student names into it.</li>
<li>Read and display all the contents of a text file.</li>
<li>Append a new student name to an existing file.</li>
<li>Count the number of lines in a file.</li>
<li>Count the number of words in a file.</li>
<li>Search for a particular word in a file.</li>
<li>Create a program that stores student marks in a file.</li>
<li>Create a notes application using a text file.</li>
<li>Create a JSON file containing student information.</li>
<li>Read the JSON file and display the student's information.</li>
</ol>
<h2>14.54 Mini Project: Student Record Manager</h2>
<p>
Create a simple program that accepts student information and stores
each record in a text file.
</p>
<pre><code>name = input("Enter student name: ")
age = input("Enter age: ")
marks = input("Enter marks: ")
with open("students.txt", "a") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
file.write(f"Marks: {marks}\n")
file.write("--------------------\n")
print("Student record saved successfully.")</code></pre>
<h2>14.55 What's Next?</h2>
<p>
<strong>
Next Chapter: Python Exception Handling – try, except, else and finally
</strong>
</p>