0% found this document useful (0 votes)
5 views57 pages

InputOutput FilesInPython

The document provides an overview of input and output (I/O) operations in Python, focusing on terminal and file interactions. It covers key functions such as input(), print(), open(), read(), and write(), along with best practices for file handling, including the use of the 'with' statement for automatic resource management. Additionally, it emphasizes the importance of exception handling to ensure program stability during file operations.
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)
5 views57 pages

InputOutput FilesInPython

The document provides an overview of input and output (I/O) operations in Python, focusing on terminal and file interactions. It covers key functions such as input(), print(), open(), read(), and write(), along with best practices for file handling, including the use of the 'with' statement for automatic resource management. Additionally, it emphasizes the importance of exception handling to ensure program stability during file operations.
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

Python Input and Output: File and Terminal

Input/Output in Python: Terminal, Files


By Python Team

swap_horiz What is I/O? folder_open File Operations

Programs interact with external sources. open(): Connect to a file.

Input: Receive data. read(): Extract data from file.

Output: Present results. write(): Store data into file.

Fundamental Interaction
close(): Release file resources.

with open("[Link]", "w") as f:


[Link]("Python is great!")

terminal Terminal Interaction


input(): Capture user text from keyboard.
print(): Display information to console.

name = input("Enter your name: ")


print(f"Hello, {name}!")

touch_app database smart_toy


Interactivity Data Management Automation
Engage users directly with prompts and Achieve persistent storage and retrieval of Streamline repetitive tasks and process
feedback. data. large datasets.
Agenda

terminal
Terminal
Input/Output description
File
Input/Output code Example
Programs
(I/O) (I/O) Practical application of I/O
Direct interaction with Read from and write to files
Demonstrate Python
program
Enables persistent data capabilities
Keyboard for input, screen storage
Hands-on coding experience
for output
Handles various file types
Fundamental for basic
scripts
What is Input/Output (I/O)?

keyboard Input
Receiving data from the user or another
source.
monitor Output
Sending data to the screen or saving it
somewhere.

terminal Terminal (Console) I/O

Direct interaction via command line interface. Uses


folder_open File I/O

Reading data from and writing data to external files.


functions like input() for user entry and print() for Essential for persistent storage and retrieval.
display.
Terminal Input with input()

The `input()` function enables


interactive data capture directly from
the user.
Returns String Data: Input is always captured as a
string, requiring explicit conversion for other types. text_fields
Interactive Prompt: Displays a message and pauses
execution, awaiting text entry. waving_hand Visual representation of code execution within a terminal
environment.

Python `input()` Example

# Get user's name


name = input("Enter your name: ")

# Greet the user


print("Hello, " + name + "!")

Expected Input: John Doe


Expected Output: Hello, John Doe!
Type Conversion in Input: Ensuring
Data Integrity

info Why
Convert?
Key Functions

int()
● Input values are
Converts to a whole
always strings by
number.
default. age = input("Enter your age: ")

● Conversion is crucial age = int(age) float()


for arithmetic or print("Next year, you will be", age + 1) Converts to a decimal
specific data number.
handling.
str()
Converts any value to
text.

● Prevents TypeErrors ● Enables Numeric Operations ● Ensures Data Compatibility


terminal Terminal Output with print()
Key print() Functionality:

info
print("Hello, World!")
Purpose & Utility Output: Hello, World!

chevron_right Purpose: Display information directly to


the console.
print("The answer is", 42)
chevron_right Utility: Fundamental for debugging and Output: The answer is 42
user interaction.

chevron_right Versatility: Accommodates various data Multiple items, automatically spaced:


types and multiple arguments.
print("Name:", "Alice", "Age:", 30)

Output: Name: Alice Age: 30


Formatting Output

code Using f-strings (Python 3.6+)


A concise way to embed expressions inside string literals.
data_object Using the .format() method
A flexible method for formatting strings with placeholders.

name = "Alice" name = "Alice"


score = 90 score = 90
print(f"{name} scored {score} points.") print("{} scored {} points.".format(name, score))

Modern Concise Readable Versatile Explicit Older Python

lightbulb Prioritize clarity and readability in your code formatting. Choose the method that best suits your project's Python version
and style guide.
More About print()

subject `print()` adds a newline by


default
swap_horiz Use end to change the ending

"The `end` parameter allows you to customize


"Each `print()` statement concludes with a the character(s) appended after the output,
newline, moving the cursor to the next line for preventing the default newline."
subsequent output."

print("Hello", end=" ")


print("Hello") print("World!")
print("World!")
# Output:
# Output: Hello World!
Hello
World!
File Input/Output Overview

swap_horiz Core Functionality


Reading and writing data from/to files is essential for
applications to interact with persistent storage.

save Persistent Storage


Files enable data persistence on disk, allowing later
retrieval, analysis, and use across sessions.

"Data is the new oil, and files are its reservoirs. Efficient I/O is critical to unlocking its value."
(Consulting Insight)
Opening Files
code The `open()` Function key File Access Modes
'r' : Read-Only
file = open('[Link]', 'r')
# 'r' for reading 'w' : Write (overwrites)

'a' : Append (adds to end)

Connects your Python script to a file resource. 'b' : Binary (for non-text)
Reading from a File
Key Concepts

file_open Open File: Establish a connection to


[Link] in read mode ('r').
file = open('[Link]', 'r')

description Read Content: Extract the entire file's content


into a variable.
content = [Link]()

print
print(content)
Display Output: Present the read content to [Link]()
the user.

close Close Connection: Release system resources


by closing the file.

Streamlining data access and management.


Reading Lines from a File
Method 1: Line-by-Line Iteration Method 2: Read All Lines at Once

description Efficient Iteration


Processes content line by line.
view_list Full File Read
Loads all lines into a list.
Ideal for very large files. Convenient for smaller files.
Minimizes memory consumption. Requires sufficient memory.

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


for line in file: lines = [Link]() # returns a list of lines
print([Link]()) for line in lines:
[Link]() print([Link]())
[Link]()

check_circle Always remember to [Link]() to release system resources and


prevent data corruption.
Writing to a File
Controlling Data Persistence with Python

edit 'w' Mode: Overwrite Existing


Content add_box 'a' Mode: Append to Existing
Content

Creates a new file if it does not exist. Creates a new file if it does not exist.

Truncates (empties) an existing file upon opening. Adds new content to the end of the file.

Caution:Any existing data in the file will be lost. Preserves all previously existing data.

Caution New File Overwrite Safe Add Data Preserve

Python Code Example

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


[Link]("Hello, file!\n")
[Link]()
Efficient Data Management

check_circle Always remember to use [Link]() to ensure data integrity and release system resources.
Writing Multiple Lines to a File

Methods for Efficient Multi- code Python Example: writelines()

Line Writing
lines = ["First line\n", "Second line\n"]
file = open('[Link]', 'w')
description Open file in write ('w') or append ('a')
mode.
[Link](lines)
[Link]()

loop Iterate and write: Process each line


individually.

speed Use `writelines()`: Optimized for bulk


writing.

checklist Provide a list of strings with newline `\n`


chars.

Source: Real Python - Reading Input and Writing Output


Ensuring Safe File Handling: with

warning Traditional file handling requires explicit


[Link]() , leading to potential issues:
Python `with` Statement
with open('[Link]', 'r') as file:
content = [Link]()
Resource Leaks
print(content)
Data Corruption Risk
# File is auto-closed after block, even if errors
Errors Prevent Closure

check_circle Automatic Resource Management

Guaranteed file closure after block execution.


bolt Robust Error Resilience

File handles are released even on exceptions.


Eliminates need for manual close() calls. Prevents resource leaks during runtime errors.
Simplifies error-prone code patterns. Enhances application stability and integrity.
Exception Handling in File I/O

warning Why Exception Handling is


Crucial
Python try-except for File
Operations
Ensures Program Stability: Prevents crashes.
try:
Graceful Error Recovery: Responds smoothly. with open('[Link]', 'r') as f:
data = [Link]()
Enhances User Provides clear except FileNotFoundError:
Experience: feedback. print("File not found.")

Proactively manages common file I/O problems like


missing files or permission issues.

check_circle Result: Predictable & Robust I/O


Guarantees your application handles missing files or
access issues without crashing, maintaining operational
flow and trust.
Example: Copying File Content

with open('[Link]', 'r') as fin, \


open('[Link]', 'w') as fout: This Python snippet efficiently copies data line-by-
for line in fin: line.
[Link](line)
It utilizes the with statement for robust resource
management, ensuring files are closed properly.

file_open code save


[Link]: Source File

'r': Read Mode

[Link]: Destination File [Link]


arrow_forward Python Script
arrow_forward [Link]
'w': Write Mode

Streamlined Data Transfer


Reading/Writing CSV Files (Using `csv` Module)
Python Code Example: Reading [Link]

import csv # Specialized module

# Open CSV file for reading


with open('[Link]', newline='') as csvfile:
# Create a reader object
reader = [Link](csvfile)
"Python simplifies data handling with specialized
modules for common file formats, making complex # Iterate over each row
for row in reader:
operations intuitive." print(row) # Output the row as a list

Key Advantages of Python's `csv` Module

Effortless Parsing & Serialization

Handles Diverse Delimiters

Built-in Error Handling

Direct Integration with File I/O

auto_stories Utilize Python's robust csv module for streamlined and reliable CSV file processing in your applications.
Summary

terminal Terminal I/O Basics folder_open File Operations


● input() function ● open() for access

● print() function ● read() / write() data

● close() resources
Facilitates direct user interaction and output
display. Enables persistent data storage and retrieval.

check_circle Efficient Resource Handling error Robust Program Design


Use with statement. Implement try...except blocks.

Guarantees automatic resource cleanup, Manages runtime errors gracefully, enhancing


preventing leaks. stability.
Practice Exercises
Python File I/O Fundamentals

person User Data Storage description File Content Analysis

Prompt for name and age Read any text file

Save to a text file Count lines, words, characters

Format data clearly Display summary statistics

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


name = input("Your name: ") content = [Link]()
age = input("Your age: ") lines = [Link]('\n') + 1
with open("user_data.txt", "w") as f: words = len([Link]())
[Link](f"Name: {name}\n") chars = len(content)
[Link](f"Age: {age}\n") print(f"Lines: {lines}, Words: {words}, Chars: {chars}")

contact: x@[Link]
Python File Handling: 10
Exercises
Exercise: Working with Files
Python Team
Exercise 1: Counting Lines
Mastering File Handling in Python

Key Steps

edit_note Write a Python program to count the file_open Open the file in read mode.
number of lines in a text file named
[Link] . view_list Iterate over lines or use readlines() .

tag Count the lines.

Why File Handling Matters

save Data Persistence: Store data beyond program


execution.

settings Configuration: Read settings and user


preferences.

analytics Data Processing: Analyze logs, datasets, and


reports efficiently.
Exercise 1: Answer
Counting Lines in a File
Goal Python Solution (`[Link]`)

file_open Open `[Link]` in read mode


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

list_alt Retrieve all lines into a list 2


3
lines = [Link]()
print("Number of lines:", len(lines))

numbers Output the total line count

Key Mechanisms

with open(...): Ensures automatic file closure

[Link](): Reads all lines as list elements

len(lines): Calculates the number of items in the list

Why This Matters


Foundation for text analysis

file_open import_contacts task_alt Crucial for data logging & reports

Enables efficient script automation


Access Data Process Content Output Result
Exercise 2: Word Count

description Task Requirements lightbulb Guidance for Solution

Develop a Python program. Open the file and read all content.

Utilize the `split()` method to separate words


Functionality: Count total words in `[Link]`. effectively.

Implement logic to accurately count the separated


words.
Exercise 2: Answer: Python Word Counter
Python Code File I/O

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


content = [Link]()
words = [Link]()
print("Number of words:", len(words))

Code Breakdown

file_open Open File: Opens '[Link]' in read mode ('r').

description Read Content: Reads entire file content into a single string.

segment Split Words: Divides the content string into a list of words.

tag Count Words: Calculates the total number of words using len().

check_circle The with open(...) statement ensures the file is automatically closed, preventing resource leaks and handling errors
gracefully.
Exercise 3: Copy File
description Program Objective checklist Implementation Guidance

Develop a Python program to duplicate file content.


check Open both files: one for reading ('[Link]'), one for
writing ('[Link]').

Copy the contents of [Link] into [Link] . check Read data from the source file ('[Link]').

check Write the read data to the destination file


('[Link]').

check Consider using a loop or reading all content at once.

Conceptual representation of file transfer. Visualizing data flow during file operations.

info Python File Handling Best Practices

Use 'with open(...)' for automatic resource


Specify appropriate file modes (e.g., 'r', 'w', 'a').
management.

Choose efficient reading methods (read(),


Implement exception handling for file operations.
readline()).

Source: Reading and Writing Files in Python (Guide) – Real Python


Exercise 3: Answer
Implementing Robust File Copying in Python

terminal Python Code for File Copy lightbulb Understanding the Approach
`with` Statement: Ensures files are
with open('[Link]', 'r') as src, open('[Link]', 'w') as dst:
for line in src:
automatically closed.
[Link](line)
`open(..., 'r')`: Opens file for reading existing
content.

`open(..., 'w')`: Opens for writing, creates or


overwrites.
folder_open Source File (Read) save Destination File (Write) Line-by-Line Copy: Efficient for large files,
check_circle `with` statement avoids high memory use.

policy Python File I/O Best Practices

check_circle Always use `with open(...)` to handle files


securely.

check_circle Implement error handling (e.g., `try-except`) for


file operations.

check_circle Select appropriate file modes (`'r'`, `'w'`, `'a'`) Ensuring Data Integrity
for specific tasks.
Exercise 4: Writing User Input
Program Goal: Capture & Persist

check_circle Prompt user for 5 unique lines of text.


Strategic Implementation Hints

Loop Control: Use a for loop to manage 5


lightbulb
check_circle Save all inputs to a file: user_input.txt . • input iterations.

User Interaction: Employ input() to get


• each line.

File Access Mode: Open user_input.txt


• using write mode ( 'w' ).

edit_square •
Content Persistence: Write each collected
line to the file.

description
"File I/O is a foundational skill for data
storage and dynamic application
development."
— Python File Handling Guide
Exercise 4: Answer
terminal Python Script for User Input
Deconstructing the Logic
with open(...)

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


for i in range(5):
lock_open Safely opens the file, ensuring automatic closure.

line = input("Enter a line: ")


'user_input.txt', 'w'

edit_document
[Link](line + "\n")
Specifies filename and 'write' mode (overwrites
existing).

for i in range(5): & input(...)

keyboard Loops 5 times, prompting the user for input each


iteration.

[Link](line + "\n")

save Writes the user's input line, followed by a newline


character, to the file.

lightbulb Why This Matters


User interaction meets persistent storage.
Fundamental for data logging and configuration.

The with statement is crucial for resource management.


Exercise 5: Reverse File Content

description File I/O operations are fundamental for data


persistence and manipulation.

Requirements
Write a program to read lines from [Link] and write
them in reverse order to [Link] .

Key Hints

read_more Read all lines using readlines() .

swap_vert Reverse the list of lines.

save_as Write reversed lines to the new file.

file_open
Step 1: Read Input
swap_vert
Step 2: Process Data
save
Step 3: Write Output
Access [Link] and retrieve all content Reorder the collected lines, placing the last Create [Link] and write the
as a list of lines. line first and so on. reversed list of lines into it.
Exercise 5: Answer

folder_open Streamlined File Management


The with open() construct ensures files are
automatically closed, even if errors occur,
with open('[Link]', 'r') as infile:
lines = [Link]() preventing resource leaks.
with open('[Link]', 'w') as outfile:

autorenew
for line in reversed(lines):
[Link](line) Efficient Line Reversal
The reversed() function iterates through the
list of lines in reverse order, enabling efficient
backward writing.
Objective: Read '[Link]', reverse its lines, and
write to '[Link]'.

Read Mode (`'r'`) Write Mode (`'w'`) In-memory Processing Python File I/O Fundamentals
Exercise 6: Uppercase File Output
edit_note Objective lightbulb Key Hints
Transform the content of • Read file content as a single string.
[Link] to all
• Utilize Python's [Link]()string method.
uppercase letters, then save
the result to [Link]. • Write the modified string to the new output file.

file_open
[Link]
Content Read
.upper() Applied

arrow_forward_ios
save
[Link]

Process
Input File Output File
Source: Python File Handling Guides
Exercise 6: Answer - Python File Transformation
Execution Breakdown
Python Code Solution
file_open 1. Open [Link] for reading ( 'r' ). The
with statement ensures proper file closure.
with open('[Link]', 'r') as in_f:
data = in_f.read()
with open('[Link]', 'w') as out_f:
out_f.write([Link]())
content_copy 2. Read the entire content into the data variable.

text_format 3. Transform the read data to uppercase using


.upper() method.

save 4. Open [Link] for writing ( 'w' ). This


creates or overwrites the file.

edit 5. Write the uppercase content into


[Link] .

Key File Handling Concepts


with open() 'r' (Read Mode) 'w' (Write Mode) .read() .write() .upper()
Exercise 7: Find Longest Line
checklist Problem Statement Solution Guidance

"Write a Python program to identify and display


the longest line from the specified file
file_open Read All Lines: Use readlines() to get
all lines as a list.
[Link] ."

code Find Maximum: Apply max() with


key=len for efficient comparison.

text_fields Clean Output: Employ .strip() to


remove newline characters for display.
File I/O String Operations Algorithm

Data Flow Concept


developer_mode_tv Relevant Python Functions

check_circle open() : To access the file.


check_circle [Link]() : To read all lines into a list.
check_circle item with the maximum value.
max(iterable, key=func) : For finding the

arrow_right_alt Input: [Link] content

arrow_right_alt Process: Length comparison check_circle whitespace.


[Link]() : To remove leading/trailing

arrow_right_alt Output: Longest line data


Exercise 7: Answer
code Python Solution for Identifying the Longest Line in a File

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


lines = [Link]()
longest = max(lines, key=len)
print("Longest line:", [Link]())

Code Walkthrough

Opens '[Link]' in read mode, ensuring the file is


properly closed after use.

Reads all lines from the file into a list named lines .

Uses the max() function with key=len to find the string


with the maximum length.

Prints the longest line after removing leading/trailing


whitespace with .strip() .
Exercise 8: Select Lines Containing a Word

assignment Task Objective lightbulb Implementation Guidance

check_circle Read content from [Link] file. check_circle Iterate line-by-line over the input file.
check_circle Identify lines containing "python" (case- check_circle Use .lower() for case-insensitive matching.
insensitive).
check_circle Apply Python's in operator for word detection.
check_circle Write identified lines to python_lines.txt .
check_circle Write only matching lines to the output file.

Why File Handling is Crucial


Data Persistence: Store information beyond program execution.

Logging & Auditing: Record system events and user actions.

Configuration: Manage application settings and parameters.

Data Exchange: Facilitate import/export of structured data.


Exercise 8: Answer
Python File Handling: Filtering Lines

info Python Code Solution

This solution efficiently reads a source file, with open('[Link]', 'r') as infile, open('pyt
extracts specific content, and writes it to a new for line in infile:
if "python" in [Link]():
file.
[Link](line)
Source File: Reads [Link]

Filtering Logic: Identifies lines with "python"

Output File: Writes matches to python_lines.txt

sync
Context Manager (with)
edit_note
Clear Code Practices
filter_alt
Line-by-Line Processing
Ensures files are properly closed, Uses descriptive variable names for easy Iterates efficiently, suitable for handling
preventing resource leaks. understanding. large datasets.
Exercise 9: File Merge
Requirements Hints
Write a program to merge the contents of [Link] and Open both input files and read lines.
[Link] into [Link]. Write all lines to the output file.

Streamlining Data Flows

file_open
Read
edit_note
Write
note_add
Append
Access and retrieve existing file Store new data, overwriting existing Add data to the end, preserving
content. content. existing content.
Python Exercise: Combining Files
Demonstrating a robust approach to merge multiple text files.

with open('[Link]', 'w') as outfile:


for fname in ['[Link]', '[Link]']:
with open(fname, 'r') as f:
for line in f:
[Link](line)

lock_open `with open()`


Statement
sync Read & Write
Operations
save Line-by-Line
Processing
Ensures files are properly 'w' for writing (overwrites), 'r' Iterating `for line in
closed, even if errors occur. for reading existing files. file_object` reads
Manages resources Essential for data flow. content memory-
automatically. efficiently.
Exercise 10: Numbered Lines
description Challenge Overview lightbulb Guidance for Implementation
Objective: Read [Link] to create Utilize Python's enumerate() for efficient line
[Link]. numbering.

Each line in [Link] must be prefixed by its Construct each output line using f-strings for
line number. clarity.

Ensure files are opened in appropriate modes and


properly closed.

File I/O Text Processing Python enumerate() File Modes String Formatting

file_open sync save


Input Source
Reads content from
[Link].
arrow_forward Process &
Transform
Adds line numbers to each
entry.
arrow_forward Output Destination
Writes numbered lines to
[Link].
Python File Handling: Line Numbering Example
Practical Demonstration of File I/O Operations

with open('[Link]', 'r') as infile, open('[Link]', 'w') as outfile:


for idx, line in enumerate(infile, 1):
[Link](f"{idx}: {line}")
File I/O Process

• open('[Link]', 'r') : Opens '[Link]' for reading.

• open('[Link]', 'w') : Creates/overwrites


'[Link]' for writing.

• enumerate(infile, 1) : Iterates through lines, providing a 1-


based index.
input Input File
(`[Link]`) output Output File
(`[Link]`)
Reads existing content, Writes new, processed
• [Link](...) : Writes numbered line to output file.
line by line, without content. Overwrites if file
• with statement: Ensures files are properly closed modification. exists.
automatically.
Read Mode ('r') Write Mode ('w')

check_circle Best Practices

• Always use with open(...) : Guarantees resource closure.


• Understand file modes: 'r', 'w', 'a', 'x', 'b', 't' are crucial.
• Handle exceptions: Use try...except for robust code.
Thank You!
"These exercises cover fundamental file handling operations in Python.
Practice them to reinforce your understanding. Feel free to ask any
questions!"

Master file I/O operations Build practical proficiency Engage with questions

mail your_email@[Link]
Multiple Choice Questions:
Python File Handling
Test Your Knowledge: File in Python

Python Team
MCQ 1: File Modes
"Which mode opens a text file for
reading in Python?"

A) 'w'

B) 'a'

C) 'r' check_circle
D) 'x'

info Explanation
The mode 'r' stands for read-only mode. It opens the file
for reading (default mode).
MCQ 2: Writing to File
A) Raise an error

What will the following code do if


[Link] does not exist? B) Open file in append mode

open('[Link]', 'w') check_circle C) Create a new file named [Link]


D) Do nothing

Opening with 'w' (write) will create the file if


it does not exist, or overwrite if it does.
quiz
Python File Handling Quiz
Understanding File Modes

A) 'r' - Read Mode B) 'a' - Append Mode


check_circle
C) 'w' - Write Mode D) 'rb' - Read Binary Mode

Which mode should you Explanation:


use to add new lines to The 'a' (append) mode adds new content to the end of the file without
the end of an existing file? erasing existing content. If the file does not exist, it creates a new one.

Key Python File Modes & Their Uses

book_2
Read ('r')
edit
Write ('w')
add_chart
Append ('a')
Opens for reading. Errors if file doesn't Opens for writing. Creates new or truncates Adds to end of file. Creates if it doesn't
exist. existing. exist.
MCQ 4: Best File Handling Practice help
"Why is it best to use the `with` block when working with files?"

A) It reduces code size B) It is required in Python 3

check_circle automatically
C) It ensures the file is closed
D) It increases speed

Explanation

The with block ensures the file is closed


properly, even if an error occurs, preventing
resource leaks.
MCQ: Which method reads the ENTIRE contents of
a file as a string?

The .read() method reads the whole


A) `.readline()`
file into a single string.

B) `.readlines()`

check_circle C) `.read()`
D) `.input()`
MCQ 6: Line by Line Reading

Which loop will correctly print all lines


from an open file f ?

radio_button_unchecked A) for item in [Link](): print(item)


radio_button_unchecked B) for ch in [Link](): print(ch)
check_circle C) for line in f: print(line)
radio_button_unchecked D) for row in [Link](): print(row)

info Explanation: Iterating directly over the file object yields each line, one by one.
quiz MCQ 7: Handling Files Safely

What happens if you try to open a non-


existent file in read mode without error
handling?

A) File is created

B) Program continues

check_circle C) `FileNotFoundError` is raised


D) Nothing happens

Explanation
Opening a non-existent file in read mode ('r') causes a `FileNotFoundError` .
MCQ 8: Binary File Operations
Which file operation below will write binary data?

A) open('[Link]', 'r')

B) open('[Link]', 'w')

C) open('[Link]', 'wb') check_circle


D) open('[Link]', 'rw')

info Explanation: Using 'wb' opens the file in binary write mode, needed for non-text data. The 'w' mode is
for text files, and 'r' for reading.
MCQ 9: Writing Multiple Lines in Python

Given lines = ['a\n', 'b\n', 'c\n'] ,


which method writes all lines to a file?

check_circle A) [Link](lines)

B) [Link](lines)

C) [Link](lines)

D) [Link](lines)

info Explanation:
The .writelines() method writes each string in the list to the file.
MCQ 10: File Closing quiz
Is the file guaranteed to Options
close?
check_circle A) Yes

radio_button_unchecked
After using this Python code, is the file
guaranteed to close? B) No

radio_button_unchecked C) Only if there’s no exception

with open('[Link]') as f: radio_button_unchecked D) Only in Python 3

[Link]()

info Explanation The with statement automatically closes the file when the
block finishes, even if there’s an exception. This ensures
proper resource management.

contact: x@[Link]
AI Model with CNN for CSV Data: Step-by-Step Manual

This manual takes your students from raw CSV data to a working AI model, with testing and
deployment sample code.

Step 1: Understanding the Problem and Data

 Goal: Build a neural network to classify records based on two features (Temperature, Humidity)
into categories (Label: 0, 1, 2, 3).

 Input: CSV file with 3 columns ("Temperature", "Humidity", "Label")

 Output: The model predicts the label (class) for given temperature/humidity.

Step 2: Prepare Your Python Environment

You need:

 Python 3.x

 Libraries: numpy, pandas, scikit-learn, tensorflow or keras

Install packages (if necessary):


pip install numpy pandas scikit-learn tensorflow

Step 3: Loading and Preparing CSV Data

Assume your file is named [Link]:


import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import LabelEncoder

# Load CSV
df = pd.read_csv('[Link]')

# Features and label


X = df[['Temperature', 'Humidity']].values
y = df['Label'].values
# 3. Reshape X for Conv1D: (samples, features, 1)
X_cnn = [Link]([Link][0], [Link][1], 1)

Step 4: Split Data into Train & Test


X_train, X_test, y_train, y_test = train_test_split(
X_cnn, y, test_size=0.2, random_state=42)

Step 5: Build a Simple CNN Model

Tabular data is not an image, but a simple 1D-CNN can process it by treating features as a "time series".

CNN Model Structure (explained below in detail):


import tensorflow as tf
from [Link] import layers, models

num_classes = len(set(y))

model = [Link]([
layers.Conv1D(16, kernel_size=2, activation='relu',
input_shape=(2,1)),
[Link](),
[Link](32, activation='relu'),
[Link](num_classes, activation='softmax')
])

[Link](optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

Step 6: Train the Model


[Link](X_train, y_train, epochs=30, batch_size=16,
validation_split=0.1)
Step 7: Save and Test the Model

Save:
[Link]('cnn_tabular_model.h5')

Test/Evaluate:
loss, acc = [Link](X_test, y_test)
print("Test accuracy:", acc)

Step 8: Making Predictions on New Data (Python Script)

Suppose you have a new sample to predict:


import numpy as np
from [Link] import load_model

# Load scaler and model (assuming you have saved them)


model = load_model('cnn_tabular_model.h5')

# Assume you have loaded scaler and label encoder OR re-fit from all
data!
# Here is a new sample:
new_temperature = 23.5
new_humidity = 55.2

# Must use same scaler as before!


X_new = [Link]([[new_temperature, new_humidity]])
X_new = X_new.reshape(1, 2, 1)

pred = [Link](X_new)
pred_label = le.inverse_transform([[Link](pred)])

print("Predicted label:", pred_label[0])


Step 9: Detailed Explanation of the CNN Structure

 Input Layer: Shape (2, 1) where 2 is the number of features. We reshape each sample like a "1D
signal".

 Conv1D Layer:

o 16 filters, kernel size of 2.

o Slides a window over the 2 features, trying to learn interactions.

o Activation: 'relu'

 Flatten Layer: Converts the output from the convolution into a flat vector.

 Dense Layer: 32 neurons, 'relu' activation for more learning capacity.

 Output Dense: num_classes neurons (for each label), 'softmax' outputs probabilities for each
class.

Why CNN for tabular? Although not typical, 1D CNNs can find feature interactions, similar to polynomial
features in classic ML. For only two features, the model is simple—just to demonstrate CNN principles.

Step 10: Notes and Best Practices

 For real projects, use more data/epochs and possibly regularization.

 Always scale input features identically during train and test.

 Save both your scaler and label encoder for deployment.

You might also like