InputOutput FilesInPython
InputOutput FilesInPython
Fundamental Interaction
close(): Release file resources.
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.
info Why
Convert?
Key Functions
int()
● Input values are
Converts to a whole
always strings by
number.
default. age = input("Enter your age: ")
info
print("Hello, World!")
Purpose & Utility Output: Hello, World!
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()
"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)
Connects your Python script to a file resource. 'b' : Binary (for non-text)
Reading from a File
Key Concepts
print
print(content)
Display Output: Present the read content to [Link]()
the user.
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.
check_circle Always remember to use [Link]() to ensure data integrity and release system resources.
Writing Multiple Lines to a File
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]()
auto_stories Utilize Python's robust csv module for streamlined and reliable CSV file processing in your applications.
Summary
● close() resources
Facilitates direct user interaction and output
display. Enables persistent data storage and retrieval.
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() .
Key Mechanisms
Develop a Python program. Open the file and read all content.
Code Breakdown
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
Copy the contents of [Link] into [Link] . check Read data from the source file ('[Link]').
Conceptual representation of file transfer. Visualizing data flow during file operations.
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.
check_circle Select appropriate file modes (`'r'`, `'w'`, `'a'`) Ensuring Data Integrity
for specific tasks.
Exercise 4: Writing User Input
Program Goal: Capture & Persist
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(...)
edit_document
[Link](line + "\n")
Specifies filename and 'write' mode (overwrites
existing).
[Link](line + "\n")
Requirements
Write a program to read lines from [Link] and write
them in reverse order to [Link] .
Key Hints
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
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.
Code Walkthrough
Reads all lines from the file into a list named lines .
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.
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]
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.
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.
Each line in [Link] must be prefixed by its Construct each output line using f-strings for
line number. clarity.
File I/O Text Processing Python enumerate() File Modes String Formatting
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
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?"
check_circle automatically
C) It ensures the file is closed
D) It increases speed
Explanation
B) `.readlines()`
check_circle C) `.read()`
D) `.input()`
MCQ 6: Line by Line Reading
info Explanation: Iterating directly over the file object yields each line, one by one.
quiz MCQ 7: Handling Files Safely
A) File is created
B) Program continues
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')
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
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
[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.
Goal: Build a neural network to classify records based on two features (Temperature, Humidity)
into categories (Label: 0, 1, 2, 3).
Output: The model predicts the label (class) for given temperature/humidity.
You need:
Python 3.x
# Load CSV
df = pd.read_csv('[Link]')
Tabular data is not an image, but a simple 1D-CNN can process it by treating features as a "time series".
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'])
Save:
[Link]('cnn_tabular_model.h5')
Test/Evaluate:
loss, acc = [Link](X_test, y_test)
print("Test accuracy:", acc)
# 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
pred = [Link](X_new)
pred_label = le.inverse_transform([[Link](pred)])
Input Layer: Shape (2, 1) where 2 is the number of features. We reshape each sample like a "1D
signal".
Conv1D Layer:
o Activation: 'relu'
Flatten Layer: Converts the output from the convolution into a flat vector.
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.