Class XII Computer Science
DATA FILE HANDLING
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb drive etc.
TYPES OF FILES
TEXT FILE - A text file stores information in ASCII or UNICODE characters. Each line of text is
terminated, (delimited) with a special character known as EOL
BINARY FILE- A binary file contains information in the same format in which the information is held in
memory. Binary files are faster and easier for a program to read and write than are text files.
CSV FILES- CSV stands for "comma-separated values“. It is used to store tabular data, such as a
spreadsheet or database. Each line of the file is a data record. Each record consists of one or more fields,
separated by commas.
STEPS TO PROCESS A FILE
OPEN THE FILE------> PROCESSING THE FILE------>CLOSE THE FILE
OPENING FILES
1. USING OPEN FUNCTION
open() function is used to open a file.
file variable/file handle=open(file_name,access mode)
Examples
Programming example description
F= open('[Link],'w') this statement opens [Link] in write [Link] [Link] will exist
in same folder as python file
F= open('D:\\Computer\\[Link]’) change the location of file then we have to mention complete
file path with file name . don t forget to mention double slash
in file path
F= open(r'D:\Computer\[Link],'w') if you don’t want to use // then use r in front of file
If file mode is not mentioned in open function then default file mode i.e 'r' is used.
2) USE OF WITH CLAUSE
with open(“file name”,access mode) as file object
Example
with open(“[Link]”,’r’) as f
No need to close the file explicitly(using close() function) if we are using with clause.
CLOSING FILES
close() : the close() method of a file object flushes any unwritten information and close the file object
after which no more writing can be done.
SYNTAX:
[Link]()
FILE MODE- It defines how the file will be accessed
Text File Binary Description Notes
/ CSV File
File Mode
Mode
‘r’ ‘rb’ Read only File must exist already, otherwise python raises I/O
error
‘w’ ‘wb’ Write only If the file does not exist, file is created.
If the file exists, python will truncate existing data and
overwrite in the file.
‘a’ ‘ab’ Append File is in write only mode.
If the file exists, the data in the file is retained and new
data being written will be appended to the end.
If the file does not exist, python will create a new file.
‘r+’ ‘r+b’ or Read and File must exist otherwise error is raised.
‘rb+’ write Both reading and writing operations can take place.
‘w+’ ‘w+b’ Write and File is created if doesn’t exist.
or read If the file exists, file is truncated(past data is lost).
‘wb+’ Both reading and writing operations can take place.
‘a+’ ‘a+b’ Write and File is created if does not exist.
or read If file exists, files existing data is retained ; new data is
‘ab+’ appended.
Both reading and writing operations can take place.
TEXT FILE HANDLING
METHODS TO READ DATA FROM FILES
read()- <filehandle>.read( [n] )- Reads at most n bytes, If no n is specified, reads the entire file. Returns the
read bytes in the form of a string
Example –
file1=open(“E:\\mydata\\[Link]”)
readInfo=[Link](15)
print(readInfo) #prints first 15 characters of file
print(type(readInfo)) # It will return str
redline() - <filehandle>.readline([n])- Reads a line. Returns the read bytes in the form of string.
Example -
file1 = open(“E:\\mydata\\[Link]”)
readInfo =[Link]() I
print (readInfo)
readlines()- <filehandle>.readlines()- Read all lines and returns them in a list.
Example –
file1 =open(“E:\\mydata\\info text”)
readInfo =[Link]()
print(readInfo)
type (readInfo) #output will be a list
METHODS TO WRITE DATA INTO FILES-
write()- <filehandle>.write(str1)- Write string str1 to file referenced by<filehandle>
writelines()- <filehandle>.writelines (L)- Writes all strings in list L as lines to file referenced by <filehandle>
RELATIVE AND ABSOLUTE PATH –
The os(operating system) module provides functions for working with files and directories. [Link] returns
the name of the current directory
Example
import os
cwd=[Link]
print(cwd) #cwd isurrent working directory and the string is the path
A relative path starts from the current folder whereas an absolute path starts from the topmost folder.
Examples
f= open(“[Link]”,”r”) # \\[Link] is the relative path
f=open’(E:\project\myfolder\[Link]’, “r”) # E:\project\myfolder\[Link] is absolute path
SETTING OFFSET IN A FILE:
To access the data in random fashion then we use seek () and tell () Method.
tell()- It returns an integer that specifies the current position of the file object in the file.
Example
[Link]()
seek()- It is used to position the file object at a particular position in a file.
[Link](offset [, reference point])
where offset is the number of bytes by which the file object is to be moved
reference point indicating the starting position of the file object.
Values of reference point as 0-beginning of the file, 1- current position of the file, 2- end of file.
Example
# Create a file named '[Link]'
with open('[Link]', 'w') as f:
[Link]('Hello World\nPython is fun!')
# Using read, write, tell, and seek
with open('[Link]', 'r+') as f:
# 1. tell() - Check initial position (should be 0)
print(f"Initial position: {[Link]()}")
# 2. read() - Read the first 5 characters
content = [Link](5)
print(f"Read content: '{content}'") # Outputs 'Hello'
# 3. tell() - Position has moved after reading
print(f"Position after reading: {[Link]()}") # Outputs 5
# 4. seek() - Move the pointer to position 6 (the start of 'World')
[Link](6)
print(f"Moved pointer to: {[Link]()}")
# 5. write() - Overwrite 'World' with 'Python'
[Link]('PYTHON')
# 6. seek(0) - Go back to the beginning to read the whole file
[Link](0)
print("\nFinal file content:")
print([Link]())