0% found this document useful (0 votes)
6 views12 pages

Python File Handling Basics

Chapter 6 covers Python file handling, including how to create, read, update, and delete files using various modes such as 'r', 'w', 'a', and 'x'. It also discusses reading and writing CSV files, handling exceptions, and the importance of closing files or using the 'with' statement for automatic closure. Additionally, exercises are provided to reinforce understanding of file handling concepts.

Uploaded by

wiameelhabti
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)
6 views12 pages

Python File Handling Basics

Chapter 6 covers Python file handling, including how to create, read, update, and delete files using various modes such as 'r', 'w', 'a', and 'x'. It also discusses reading and writing CSV files, handling exceptions, and the importance of closing files or using the 'with' statement for automatic closure. Additionally, exercises are provided to reinforce understanding of file handling concepts.

Uploaded by

wiameelhabti
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

Chapter 6 : Python File

Handling

📂 Introduction to File Handling


File handling is an essential part of any application.
Python allows you to create, read, update, and delete files of
various types (text, binary, CSV…).

💡 Key function: open(filename, mode)

It takes two parameters:

filename : the name or path of the file

mode : the way the file will be opened (read, write, append, etc.)

🔧 File Opening Modes


Mode Description Notes

"r" Read (default) Error if file doesn’t exist

"a" Append Creates the file if missing

"w" Write Creates file or overwrites existing

"x" Create Error if file already exists

Chapter 6 : Python File Handling 1


You can also specify text or binary mode:

"t" → Text mode (default)

"b" → Binary mode (e.g., images)

👉 Example:
file = open("[Link]", "wb") # write in binary mode

🧩 Other Combined Modes


Mode Description Example
"r+" Read and Write file = open("[Link]", "r+")

"w+" Write and Read file = open("[Link]", "w+")

"a+" Append and Read file = open("[Link]", "a+")

📝 Notes:
"r+" → Error if file doesn’t exist

"w+" → Creates file and truncates if it exists

"a+" → Appends if file exists, creates if missing

📖 Opening Files
Basic Syntax:

file = open("[Link]")

Equivalent to:

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

Chapter 6 : Python File Handling 2


“r” for read and “t” for text are default values.
⚠️ If file doesn’t exist → FileNotFoundError

📘 Reading Files
Assume a file named [Link] contains:

Hello World! Welcome to [Link]


Python is awesome!

Read entire file:

f = open("[Link]", "r")
print([Link]())

Output:

Hello World! Welcome to [Link]


Python is awesome!

📍 Reading from a Path


f = open("D:\\myfiles\\[Link]", "r")
print([Link]())

✂️ Read Part of File


f = open("[Link]", "r")
print([Link](5)) # reads 5 characters

Output:

Chapter 6 : Python File Handling 3


Hello

📄 Reading Line by Line


➤ One line:
f = open("[Link]", "r")
print([Link]())

➤ Two lines:
f = open("[Link]", "r")
print([Link]())
print([Link]())

➤ All lines in a loop:


f = open("[Link]", "r")
for line in f:
print(line)

➤ Read all lines into a list:


f = open("[Link]", "r")
lines = [Link]()
print(lines)

Output:

['Hello World! Welcome to [Link]\n', 'Python is awesome!']

🔒 Closing Files
Always close files to free memory and save changes.

Chapter 6 : Python File Handling 4


f = open("[Link]", "r")
print([Link]())
[Link]()

🧠 Tip: Some changes (especially with “w” or “a”) may not appear until
the file is closed.

✍️ Writing to Files
➤ Append to a file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

f = open("[Link]", "r")
print([Link]())

Output:

Hello World! Welcome to [Link]


Python is awesome!Now the file has more content!

➤ Overwrite content:
f = open("[Link]", "w")
[Link]("I have overwritten the content of this file!")
[Link]()

f = open("[Link]", "r")
print([Link]())

Output:

Chapter 6 : Python File Handling 5


I have overwritten the content of this file!

➤ Write multiple lines:


f = open("[Link]", "w")
lines = ["First line.\n", "Second line.\n", "Third line.\n"]
[Link](lines)
[Link]()

f = open("[Link]", "r")
print([Link]())

Output:

First line.
Second line.
Third line.

🆕 Creating Files
f = open("[Link]", "x") # creates new file
f = open("[Link]", "w") # creates if missing
f = open("[Link]", "a") # creates if missing

🗑️ Deleting Files or Folders


import os
[Link]("[Link]") # delete file

✅ Check existence first:


if [Link]("[Link]"):
[Link]("[Link]")
print("File deleted successfully.")

Chapter 6 : Python File Handling 6


else:
print("The file does not exist")

🗂️ Delete folder:
[Link]("myfolder") # only if empty

⚙️ Handling File Exceptions


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

except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You don't have permission to access this file.")
finally:
[Link]()

🧠 Using the with Statement


The with statement automatically closes the file after use.

with open("[Link]", "r") as file:


content = [Link]()
print(content)

✅ No need for [Link]()

🧩 Complete File Handling Example


import os

# 1. Creating & Writing

Chapter 6 : Python File Handling 7


try:
with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link]("This is a file handling example.\n")
print("File created and written successfully.")
except Exception as e:
print(f"Error writing to file: {e}")

# 2. Reading
try:
with open("[Link]", "r") as file:
print([Link]())
except FileNotFoundError:
print("The file does not exist.")

# 3. Appending
try:
with open("[Link]", "a") as file:
[Link]("Appending a new line to the file.\n")

with open("[Link]", "r") as file:


print([Link]())
except Exception as e:
print(f"Error appending: {e}")

# 4. Deleting
try:
if [Link]("[Link]"):
[Link]("[Link]")
print("File deleted successfully.")
else:
print("The file does not exist.")
except Exception as e:
print(f"Error deleting: {e}")

Chapter 6 : Python File Handling 8


📊 CSV File Handling
📚 What is CSV?
CSV = Comma-Separated Values → used to store tabular data (rows
& columns).
Each line = one row, fields separated by commas.
Common for data exchange between applications.

import csv

🧩 Reading CSV Files


➤ Using [Link]()

with open('[Link]', 'r') as file:


reader = [Link](file)
for row in reader:
print(row)

Each row → list.

Example Output:

['Name', 'Age', 'Country']


['Ali', '25', 'USA']
['Ahmed', '30', 'Canada']
['Iyad', '35', 'UK']

🪄 Skipping Header Row


with open('[Link]', 'r') as file:
reader = [Link](file)
next(reader) # skip header

Chapter 6 : Python File Handling 9


for row in reader:
print(row)

Output:

['Ali', '25', 'USA']


['Ahmed', '30', 'Canada']
['Iyad', '35', 'UK']

📖 Reading CSV as Dictionary


with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
print(row['Name'], row['Country'])

Output:

{'Name': 'Ali', 'Age': '25', 'Country': 'USA'}


Ali USA
{'Name': 'Ahmed', 'Age': '30', 'Country': 'Canada'}
Ahmed Canada
{'Name': 'Iyad', 'Age': '35', 'Country': 'UK'}
Iyad UK

✍️ Writing CSV Files


➤ Single Row
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['Name', 'Age', 'Country'])
[Link](['Rania', 28, 'Australia'])
[Link](['Chaimae', 22, 'France'])

Output:

Chapter 6 : Python File Handling 10


Name,Age,Country
Rania,28,Australia
Chaimae,22,France

➤ Multiple Rows
data = [['Name','Age','Country'],
['Ali',25,'USA'],
['Ahmed',30,'UK']]

with open('[Link]', 'w', newline='') as file:


writer = [Link](file)
[Link](data)

➤ Writing Dictionaries

data = [{'Name':'Ali','Age':25,'Country':'USA'},
{'Name':'Ahmed','Age':30,'Country':'UK'}]

with open('[Link]', 'w', newline='') as file:


writer = [Link](file, fieldnames=['Name','Age','Country'])
[Link]()
[Link](data)

Remarque : file csv by default convert integer to string

for example :

with open ("student_grades.csv","w+",newline="") as file: writer = [Link](file)


[Link](["Name","Age","Grade","Subject"]) rows=[["Ahmed",20,19,"Math"],
["Amal",22,18,"Physics"],["Morad",21,15,"Chemistry"],["Sophia",23,13,"Biology"],
["Yassmine",22,16,"Math"]] [Link](rows)

Chapter 6 : Python File Handling 11


20 et 19 here are strings so if we want to work with we should convert
them to string

with open ("student_grades.csv","r",newline="") as file: reader = [Link](file) next(reader)


count = 0 summe = 0 for row in reader: summe += int(row[2]) count += 1 average =
summe / count print(f'The average grade is {average}')

🧮 Exercises
1️⃣ Which mode allows both reading and writing?
✅ Answer: "r+"

2️⃣ What happens when opening a file in mode that already exists? "w"

✅ Answer: The file is overwritten.


3️⃣ What’s the default mode of ? open()

✅ Answer: (read mode) "r"

4️⃣ Which code reads all lines into a list?


✅ Answer: lines = [Link]()

5️⃣ Which mode gives an error if file doesn’t exist?


✅ Answer: and "r" "r+"

6️⃣ What happens if you try to write in mode? "r"

✅ Answer: Error – “r” is for reading only.

Chapter 6 : Python File Handling 12

You might also like