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

File Handling

The document provides comprehensive notes on file handling in Python, covering the purpose of files, types of data files (text and binary), and methods for opening, reading, and writing files. It also discusses standard input/output streams, file paths, and includes programming examples for various file operations, including binary file handling using the pickle module. Additionally, it introduces CSV files and the csv module for efficient handling of tabular data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

File Handling

The document provides comprehensive notes on file handling in Python, covering the purpose of files, types of data files (text and binary), and methods for opening, reading, and writing files. It also discusses standard input/output streams, file paths, and includes programming examples for various file operations, including binary file handling using the pickle module. Additionally, it introduces CSV files and the csv module for efficient handling of tabular data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

File Handling Notes (Class XII CBSE Computer Science)

5.1 Introduction

 Purpose of Files: Files store data permanently, used by programs


like word processors, databases, and compilers.
 File Definition: A file is a collection of bytes stored on devices
like hard disks or thumb drives.
 Python's Role: Python provides built-in functions to create and
manipulate files.

5.2 Data Files

 Types of Data Files:


o Text Files: Store data in ASCII or Unicode characters, with
each line terminated by an EOL (End of Line) character,
typically \n or \r\n. Internal translations occur during
read/write operations.
o Binary Files: Store data in the same format as in memory
(raw, no translations). Faster and easier to read/write, ideal
for program-specific data not meant for human reading or
cross-platform use.
 Key Differences:
o Text files use delimiters (EOL); binary files do not.
o Binary files are more efficient but less human-readable.

5.3 Opening and Closing Files

 Opening Files:
o Use the open() function: <file_object> = open(<filename>,
<mode>).
o If no mode is specified, defaults to read mode ('r').
o File path can be absolute (e.g., E:\\main\\result.txt) or relative
to the current working directory.
o Use double slashes (\\) or raw strings (r"path") to handle
special characters in paths.
o Example: myfile = open("taxes.txt", "r") opens taxes.txt in
read mode.
 File Object: A file object (or handle) links the program to the file
on disk, enabling read/write operations.
 Closing Files:
o Use <filehandle>.close() to close a file explicitly.
o Closing ensures data is written to the file, preventing data
loss if the program crashes.
o Example: outfile.close().

5.4 Reading and Writing Files

 File Access Modes (Table 5.1):


o Text Modes:
 'r': Read-only, file must exist.
 'w': Write-only, creates new file or overwrites existing
one.
 'a': Append, adds data to the end, creates file if it
doesn’t exist.
 'r+': Read and write, file must exist.
 'w+': Read and write, creates/overwrites file.
 'a+': Read and append, adds data to the end.
o Binary Modes: Add 'b' (e.g., 'rb', 'wb', 'ab') for binary file
operations.
 Reading Functions (Table 5.2):
o read([n]): Reads n bytes or entire file if n is not specified,
returns a string.
o readline(): Reads one line up to EOL, returns a string.
o readlines(): Reads all lines into a list, each line as a string.
o Example: myfile.read(30) reads 30 bytes; myfile.readline()
reads one line.
o Looping over file handle: for line in filehandle: print(line)
reads line by line.
 Writing Functions (Table 5.3):
o write(str): Writes string str to the file, no automatic newline.
o writelines(list): Writes a list of strings to the file, no
automatic newlines.
o Example: fileout.write("Hello\n") writes "Hello" with a
newline.
o Append mode ('a') preserves existing data, unlike write mode
('w').
 Flush Function:
o flush(): Forces buffered data to be written to the file
immediately.
o Example: f.flush() ensures data is written before continuing.
 Removing Whitespaces:
o strip(): Removes leading/trailing whitespaces (spaces, tabs,
newlines).
o rstrip(): Removes trailing whitespaces.
o lstrip(): Removes leading whitespaces.
o Example: line.rstrip('\n') removes trailing newline.
 File Pointer:
o Tracks the current position in the file for reading/writing.
o Moves forward after each read/write operation.
o Position depends on mode: 'r', 'w' start at the beginning; 'a'
starts at the end.

5.5 Standard Input, Output, and Error Streams

 Standard Streams:
o stdin: Keyboard input, treated as a file in read mode.
o stdout: Monitor output, treated as a file in write mode.
o stderr: Monitor output for errors, separate from stdout.
 Usage with sys Module:
o Import sys to use sys.stdin, sys.stdout, sys.stderr.
o Example: sys.stdout.write("Text") writes to the monitor.
 With Statement:
o Syntax: with open('file.txt', 'mode') as f: <statements>.
o Automatically closes the file, even if an error occurs.
o Example: with open('output.txt', 'w') as f: f.write('Hi!').
Absolute and Relative Paths

 Absolute Path: Full path from the root (e.g., E:\SALES\


BACKUP).
 Relative Path: Path relative to the current working directory.
o .: Current directory.
o ..: Parent directory.
o Example: If current directory is PROJ2, TWO.DOC is
accessed as ./TWO.DOC.
 Pathname: Full file/directory name, including path and extension.

Key Programming Examples

 Display File Size:


 myfile = open(r'E:\poem.txt', 'r')
 str = myfile.read()
 print("Size:", len(str), "bytes")
myfile.close()

 Count Lines:
 myfile = open(r'E:\poem.txt', 'r')
 lines = myfile.readlines()
 print("Number of lines:", len(lines))
myfile.close()

 Write to File (CSV):


 fileout = open('Marks.dat', 'w')
 count = int(input("How many students? "))
 for i in range(count):
 rollno = input("Rollno: ")
 name = input("Name: ")
 marks = input("Marks: ")
 fileout.write(f"{rollno},{name},{marks}\
n")
fileout.close()
 Append to File:
 fileout = open('Marks.dat', 'a')
 for i in range(2):
 rollno = input("Rollno: ")
 name = input("Name: ")
 marks = input("Marks: ")
 fileout.write(f"{rollno},{name},{marks}\
n")
fileout.close()

 Read and Display File:


 fileinp = open('Marks.dat', 'r')
 while True:
 line = fileinp.readline()
 if not line:
 break
 print(line, end='')
fileinp.close()

Solved Problems (Key Points)

 read() vs readlines(): read() returns a string; readlines() returns a


list of lines.
 readline() vs readlines(): readline() reads one line; readlines()
reads all lines into a list.
 File Modes:
o 'r': Opens for reading.
o 'w': Opens for writing, overwrites existing file.
 Strip Example: `for line in open('poem.txt'): print(line.robot

System: line.strip())` removes leading/trailing whitespaces.

 Longest Line:
 def stats(filename):
 longest = ""
 for line in open(filename):
 if len(line) > len(longest):
 longest = line
 print("Longest line length:",
len(longest))
print(longest)

 Copy Non-Lowercase Lines:


 def remove_lowercase(infile, outfile):
 output = open(outfile, 'w')
 for line in open(infile):
 if not line[0].islower():
 output.write(line)
output.close()

Assignment Questions

 Short Answer:
o 'w' vs 'a': 'w' overwrites; 'a' appends.
o File object: Links program to file for operations.
o open() vs close(): open() creates file object; close() releases
it.
o Binary file open: open('C:\\Myfiles\\Text1.txt', 'r+b') or
open(r'C:\Myfiles\Text1.txt', 'r+b').
o File not existing in 'w': Creates new file; existing file:
Overwrites.
 Application-Based:
o Example outputs for poemBTH.txt depend on file content
and read operations.
o contacts.csv code searches for a name and prints matching
lines.
 Programming Practice:
o Replace multiple spaces with a single space.
o Copy specific records (e.g., "Athletics" events) to a new file.
o Format telephone numbers into columns.
o Count specific words or uppercase letters in a file.
o Copy or append files based on user input.
o Sort characters into separate files based on case.

Writing Student Data to Binary File

 Program to get student data (roll no, name, marks) from user and
write to a binary file (Stu.dat).
 Uses pickle module for binary file operations.
 Declares an empty dictionary stu = {} to hold student records.
 Opens file Stu.dat in write mode ('wb') as stufile.
 Inputs data (roll number, name, marks) in a loop until user
chooses to stop.
 Adds data to dictionary: stu['Rollno'] = rno, stu['Name'] = name,
stu['Marks'] = marks.
 Writes dictionary to file using pickle.dump(stu, stufile).
 Closes file with stufile.close().

5.10: Appending Student Records

 Program to append student records to an existing file (Stu.dat)


created earlier.
 Imports pickle module.
 Declares empty dictionary stu = {}.
 Opens file Stu.dat in append mode ('ab') as stufile.
 Inputs roll number, name, and marks in a loop while user enters
'y'.
 Adds data to dictionary and writes to file using pickle.dump(stu,
stufile).
 Closes file with stufile.close() after user stops input.

5.11: Reading from Binary File (Emp.dat)

 Program to open Emp.dat (created earlier) and read/display its


objects.
 Imports pickle module.
 Declares empty dictionary emp = {}.
 Opens Emp.dat in read mode ('rb') as empfile.
 Uses while True to read records with emp = pickle.load(empfile)
until EOF.
 Prints each record with print(emp).
 Handles EOFError with empfile.close() to close the file.

5.12: Displaying Records from Stu.dat

 Program to open Stu.dat (from 5.9 and 5.10) and display stored
records.
 Imports pickle module.
 Declares empty dictionary stu = {}.
 Opens Stu.dat in read mode ('rb') as fin.
 Uses try-except with while True to read records using stu =
pickle.load(fin).
 Prints each record with print(stu).
 Closes file with fin.close() on EOFError.

5.13: Creating a Binary File (myfile.info)

 Program to create a binary file myfile.info and write a string with


two lines.
 Imports pickle module.
 Defines string: "This is my first line. This is second line.".
 Uses with open("myfile.info", "wb") as fh: to open file and write
with pickle.dump(string, fh).
 Prints success message: "File successfully created.".

5.14: Reading from myfile.info Until 'o'

 Program to read from myfile.info and display text before 'o'.


 Imports pickle module.
 Initializes st = "".
 Uses with open("myfile.info", "rb") as fh: to read with st =
pickle.load(fh).
 Splits string at 'o' with lst = st.split('o').
 Prints first part with print(lst[0]).

5.15: Searching Records by Roll Number

 Program to open Stu.dat and search for records with roll numbers
12 or 14.
 Imports pickle module.
 Declares stu = {} and found = False.
 Opens Stu.dat in read mode ('rb') as fin.
 Defines searchkeys = [12, 14].
 Uses while True to read records with stu = pickle.load(fin).
 Checks if stu['Rollno'] in searchkeys, prints record, and sets found
= True.
 Prints "No such records found" if found == False, else "Search
successful."
 Closes file with fin.close().

5.16: Displaying Records with Marks > 81

 Program to read Stu.dat and display records with marks > 81.
 Imports pickle module.
 Declares stu = {} and found = False.
 Opens Stu.dat in read mode ('rb') as fin.
 Uses while True to read records with stu = pickle.load(fin).
 Checks if stu['Marks'] > 81, prints record.
 Prints "No records with Marks > 81" if found == False, else "Search
successful."
 Closes file with fin.close().
5.17(a): Updating Marks in Stu.dat

 Program to update Stu.dat by adding 2 bonus marks for scores >


81.
 Imports pickle module.
 Declares stu = {} and found = False.
 Opens Stu.dat in read/write mode ('r+b') as fin.
 Uses while True with rpos = fin.tell() to store file pointer position.
 Reads record with stu = pickle.load(fin).
 If stu['Marks'] > 81, adds 2 marks, seeks back with fin.seek(rpos),
and writes with pickle.dump(stu, fin).
 Sets found = True on update.
 Prints "Sorry, no matching record found" if found == False, else
"Record(s) successfully updated."
 Closes file with fin.close().

5.18: Modifying Name in Stu.dat

 Program to modify names in Stu.dat.


 Imports pickle module.
 Declares stu = {} and found = False.
 Opens Stu.dat in read/write mode ('r+b') as fin.
 Uses while True with rpos = fin.tell() to store position.
 Reads record with stu = pickle.load(fin).
 Modifies name if condition met, seeks back with fin.seek(rpos),
and writes with pickle.dump(stu, fin).
 Sets found = True on update.
 Closes file with fin.close().

Key Points

 Binary files store data in non-human-readable format.


 pickle module handles binary file operations (dump, load).
 Use 'rb' for reading, 'wb' for writing, 'r+b' for read/write.
 tell() returns current file pointer position; seek() moves it.
 try-except handles EOFError during file reading.
 with statement ensures file closure automatically.

Introduction to CSV Files

 CSV stands for Comma-Separated Values.


 A CSV file stores tabular data (numbers and text) in plain text
format.
 Each line in a CSV file represents a row, with values separated by
commas (or other delimiters like semicolons).
 Commonly used for data exchange between applications (e.g.,
spreadsheets, databases).

CSV Module in Python

 Python provides the csv module to handle CSV files efficiently.


 The module includes functions like reader(), writer(),
DictReader(), and DictWriter().

Opening and Reading CSV Files

 Use open() to open a CSV file in text mode (e.g., 'r' for reading).
 Import csv module: import csv.
 Use csv.reader() to read the file, which returns an iterator of rows.
 Example: with open('data.csv', 'r') as file: reader = csv.reader(file).
 Each row is returned as a list of strings.
 Iterate over reader to access rows: for row in reader: print(row).

Writing to CSV Files

 Open a file in write mode (e.g., 'w') using open().


 Use csv.writer() to create a writer object.
 Example: with open('output.csv', 'w', newline='') as file: writer =
csv.writer(file).
 Use writer.writerow() to write a single row as a list.
 Use writer.writerows() to write multiple rows from a list of lists.
 The newline='' parameter prevents extra blank lines in Windows.

Handling CSV with DictReader and DictWriter

 csv.DictReader() reads CSV rows into dictionaries, using the first


row as keys (fieldnames).
 Example: with open('data.csv', 'r') as file: reader =
csv.DictReader(file).
 Access data by column names: for row in reader:
print(row['name']).
 csv.DictWriter() writes dictionaries to CSV files, requiring
fieldnames parameter.
 Example: with open('output.csv', 'w', newline='') as file: writer =
csv.DictWriter(file, fieldnames=['id', 'name']).
 Use writer.writeheader() to write the header row.
 Use writer.writerow() or writer.writerows() to write dictionary
data.

Delimiters and Dialects

 Default delimiter is a comma (,), but can be changed (e.g., tab \t,
semicolon ;).
 Use delimiter parameter in csv.reader() or csv.writer():
csv.reader(file, delimiter=';').
 CSV dialects allow customization (e.g., delimiter, quotechar).
 Define a dialect with csv.register_dialect() or use dialect
parameter.

Common Operations

 Reading specific columns: Access by index (e.g., row[0]) or key


(e.g., row['column'] with DictReader).
 Skipping header row: Use next(reader) to skip the first row.
 Writing data with quotes: Use quoting=csv.QUOTE_ALL to quote
all fields.
 Handling missing values: Empty strings ('') are treated as missing
data.

Example Programs

 Reading CSV:
 import csv
 with open('students.csv', 'r') as file:
 reader = csv.reader(file)
 for row in reader:
print(row)

 Writing CSV:
 import csv
 with open('output.csv', 'w', newline='') as
file:
 writer = csv.writer(file)
 writer.writerow(['ID', 'Name', 'Marks'])
writer.writerow([1, 'John', 85])

 Using DictReader:
 import csv
 with open('students.csv', 'r') as file:
 reader = csv.DictReader(file)
 for row in reader:
print(row['Name'], row['Marks'])

 Using DictWriter:
 import csv
 with open('output.csv', 'w', newline='') as
file:
 fieldnames = ['ID', 'Name', 'Marks']
 writer = csv.DictWriter(file,
fieldnames=fieldnames)
 writer.writeheader()
writer.writerow({'ID': 2, 'Name':
'Alice', 'Marks': 90})

Key Points

 CSV files are simple and widely supported but lack complex
formatting.
 Use newline='' to avoid extra lines when writing on Windows.
 DictReader and DictWriter are useful for handling data with
headers.
 Ensure proper delimiter matches the file format to avoid parsing
errors.

You might also like