Orientation - File Handling (Autosaved)
Orientation - File Handling (Autosaved)
BY
MRS. GEETANJALI HOTA
Prepared by SCIENCE
PGT COMPUTER Geetanjali Hota
PGT.
DAV PUBLIC Computer
SCHOOL, Science
POKHARIPUT, , DAV PKT
BHUBANESWAR
Learning Objectives ::
• Need of Files
• Types of Files
• Text File Vs Binary File
• Read & Write operations on both types of file
• Random FilePrepared
Operation by Geetanjali Hota
PGT. Computer Science , DAV PKT
• Use of pickle module
• Reading & Writing CSV files
• Text and Binary File manipulations
• Assignment Questions .
Need of Files
Files are named locations on disk to store
related information. They are used to
permanently store data in a non-volatile
memory (e.g. hard disk).
* Binary file
* Text file
FILE PATHS
When you access a file on an operating system, a file path is
required. The file path is a string that represents the location of a
file. It’s broken up into three major parts:
Tip
Folder Path: the file folder location on the file system A file path is also
where subsequent folders are separated by a forward called a pathname.
slash / (Unix) or backslash \ (Windows)
Extension: the end of the file path pre-pended with a period (.)
used to indicate the file type
Text files
Its a sequential characters divided into lines.
– Each line terminates with the newline character (\n).
Example:
Web standards: html, XML, CSS, JSON etc.
•
Source code: c, app, nsist
js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Binary files
It consists of data values such as integers, floats
or complex data types, “using their memory
representation.”
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
1.How newlines (\n) are stored ?
Analyzing with 2. How end-of-file is indicated?
3 features 3. How datas are stored in
the file?
First feature
Carriage Return( \r)
• In text mode, a newline character is converted moves the cursor to
into the carriage return-linefeed combination the beginning of the
before being written to disk. line without advancing
to the next line
• Likewise, the carriage return-linefeed combination on the
disk is converted back into a newline when the file is read
by a Python program.
• However, if a file is opened in binary mode, as opposed to
text mode, these conversions do not take place. Line Feed ( \n) moves
• In binary mode, each end of line is signified by a carriage the cursor down to the
next line without
return-linefeed combination and is counted as two
returning to the
characters in binary mode. beginning of the line
10
Second Feature
• The binary mode files keep track of the end of file from the number of
characters present in the directory entry of the file.
11
Third Feature
• In text mode, the text and numbers are stored as string of
characters such that the number 45678 will occupy 5 bytes
(1 byte/character).
Example:-
1.If remaining in the current folder i.e Jono I want to access
cory -> ..\cory
2.If lib file to be accessd from the current folder Usr -> .\lib
file
3.If Remaining in the current folder usr work file to be
accessed which is under Jono-> ..\HOME\JONO\work file
Basic operations performed on a data file are:
1. Naming a file
2. Opening a file
1. Closing a file
Steps to process a file
The file should exist in the same directory as the Python script, otherwise
The file should exist in the sameofdirectory
full address asbewritten.
the file should the Python script,
otherwise full address of the file should bewritten.
❖ The with statement Opening a File
File_object = open(r"File_Name", "Access_Mode")
The file should exist in the same directory as the Python script, otherwise
otherwise Syntax
full address of the file should bewritten. Error exception will be
raised.
ACCESS MODES Opening a File
Tip
Example 1:
fo =
open(“C://Python//test.txt”,
“r+”)
. Example 2:
fo =
open(“C://Python//img.bmp”,
“rb+”)
Opening a File
1 Myfile=open(‘PKT.txt’) File
Object
2 Myfile=open(‘PKT.txt’,’r’)
3 Myfile=open(‘c:\\temp\\data.txt’,’r’)
4 Myfile=open(r’c:\temp\data.txt’, ‘r’)
Closing a File
Myfile.close()
File
Object Because if we don’t call the close function after the write
method then whatever data we have written to a file will
not be saved into the file.
File Objects and its Properties
Reading from a File
str=myfile.read(30)
# Next read() reads the next 30 characters from the last read
F=open(r”E:/poem.txt”,”r”).read(30)
# Reads one line from the file
F=open(“poem.txt”,”r”).readline()
# reads all line from the file
F=open(“poem.txt”,”r”).readlines()
# Entire file will be read
F=open(“poem.txt”,”r”).read()
Reading Data From File
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
Here, n is the number of bytes to be read.
read(n)
readline(n)
readlines()
Read file in Python
.
# Python code to illustrate read() mode character wise
Example-1
Read file in Python Reading File using my_file.read(5) method
.
# Reading the content of the File
Example 2:
Output:
Hello World
Hello Python
Good Morning
How are You
Output:
He
This function returns the first 2 characters of the next line.
Example of Reading File using readline(2) method
Readline()
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
(Using this function we can read the content of the file on a line by line basis.)
Example of Reading File using readline() method
Readline()
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
(Using this function we can read the content of the file on a line by line basis.)
Example of Reading File using readline() method
import shutil
original = r'C:/Users/Geetanjali/demofile.txt'
target=r'C:/Users/Geetanjali/demofile1.txt'
shutil.copyfile(original, target)
#Reading all the lines including the newline characters.
Readlines()
Example 5:
write()_method with next line - Output
Reading_File_using_readlines()_method
Reading_File_using_readlines()_method_output
# Reading a specific line from a File
● In the following example, we are trying to read only the 4th line
from the ‘test.txt’ file using
Reading specific line from a file
write(string)
writelines(list)
Example 1:
write()_method - Output
Example 2: write()
● .
writelines()_method - Output
Appending data to File
● To append data into a file we must open the file in ‘a+’ mode so that we will have
access to both the append as well as write modes.
Example 1:
● This code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example - Appending Data to File
Example 2:
The above code appends the string ‘Guava’ at the end ofAppending
the ‘test.txt’ file
data file at a new line in a new line.
- Output
Appending data file at a new line
More Coding on write()
More Coding on writelines()
● Example-3
The code appends a list of data into a ‘test.txt’ file.
# Creating a file
with open("C:/Users/myfile2.txt", "w") as file1:
# Writing data to a file
file1.write("Hi!!!!! \n")
file1.writelines(L)
file1.close() # to change file access modes
Syntax:
fileObject.tell()
Syntax:
os.rename(current_file_name, new_file_name)
Example 1:
import os
os.rename(“test.txt”, “test1.txt”)
You can specify the location as well as shown in the below example.
Example 2:
import os
os.rename(“C:/Documents/Python/test.txt”,
“C:/Documents/Python/test1.txt”)
Python - Renaming a file
Example 2:
import os
os.remove(“C:/Documents/Python/test.txt”)
Standard Input, Output, and Error
f=open("C:/Users/Geetanjali/Desktop/out.dat","w+")
f.write("The output is \n")
f.write("My" + "work status"+ "is :")
f.flush()
s='OK'
f.write('')
f.write(s)
f.write('\n')
f.write("Finally Over \n")
f.flush()
f.close()
# Removing EOL character
Fn=open("C:/Users/Desktop/TEST.txt","r")
line=Fn.readline()
line=line.rstrip('\n')
print(line)
# Removing White Spaces
Fn=open("C:/Users/Desktop/TEST.txt","r") line=Fn.readline()
line=line.lstrip()
line=line.rstrip()
print(len(line))
BINARY FILE MODE
Advantages of Binary files
Binary file handling
Binary files are faster than text file in processing
We can generate Text files using any text editor but the same
is not true for binary files.
10 amit
20 ramji
Python Program to Write and Read a binary
file
import pickle
output_file = open("myfile.dat","wb")
myint = 42
mystring = "Hello, world!"
mylist = ["dog", "cat",
"lizard"]
mydict = { "name": "Bob", "job": "Astronaut" }
pickle.dump(myint, output_file)
pickle.dump(mystring,
output_file)
pickle.dump(mylist, output_file)
pickle.dump(mydict, output_file)
Program to Write and Read a binary file
import pickle
input_file = open(“myfile.dat","rb")
myint = pickle.load(input_file)
mystring = pickle.load(input_file)
mylist = pickle.load(input_file)
mydict = pickle.load(input_file)
print("myint =",myint)
print("mystring =",mystring)
print("mylist = ",mylist)
print("mydict = ",mydict)
APPENDING RECORDS
PROGRAM OUTPUT
APPENDING (Read)/PROGRAM OUTPUT
PROGRAM TO SEARCH A REORD
Deleting an element from Binary file
Printing the output(Deletion)
PROGRAM TO UPDATE A RECORD
File Handling – Binary File( pickle) - SEARCH 91
found = 0
for x in list1:
if name in x['name']:
found = 1
print("Found in binary file" if found == 1 else "Not found")
NOTE: Pay close attention on the if else used for printing final result
File handling – Binary File(pickle) - Update 92
import pickle
Mode “rb+” is used to read
name = input('Name to update :') and write at the same time.
file = open("student.dat", "rb+")
list = pickle.load(file)
file.close()
File handling – CSV File
95
CSV( Comma separated value) file are used to transfer data between the
applications. These files can be generated using any Text Editor, Excel and any
other supported software.
Sample CSV file generated using Excel First row contains the
Rollno,name,class,stream,agg,percenrage,result header
1,ramji,12B,SCIENCE,484,96.8,PASS
2,anuj,11A,COMM,452,90.4,PASS
3,ujjwal,12C,HUMAN,385,77,PASS
4,shlok,11B,SCIENCE,490,98,PASS
5,nipun,11A,COMM,347,69.4,PASS Single record
6,arushi,12C,COMM,456,91.2,PASS
7,ayushi,11B,HUMAN,345,69,PASS
8,sehaj,12A,SCIENCE,421,84.2,PASS
9,swarnima,12A,SCIENCE,345,69,PASS
10,harsh,11C,HUMAN,455,91,PASS
csv files
File handling – CSV File(Writer)-WRITE 99
csvwriter = csv.writer(f,lineterminator=“\n”)
Note: Since “\n\r” is default line feed in. To avoid an Extra white line in your output, add line
terminator while opening a file for writing.
File handling – CSV (Writer)-WRITE 100
import csv
records =[
["ID","name","Price","Qty"],
["102","LG Monitor","6500","20"],
["103","KeyBoard","1350","156"], Header and Records merged in
a single List
["105","Hp Mouse","650","120"],
["106","Speaker","1670","136"]
]
f = open("stock.csv","w")
csvwriter = csv.writer(f,lineterminator=“\n”)
csvwriter.writerow(header) # deleted this line
csvwriter.writerows(records) ID,name,Price,Qty
f.close() 102,LG Monitor,6500,20
print("Check your file now....") 103,KeyBoard,1350,156
105,Hp Mouse,650,120
106,Speaker,1670,136
File handling – CSV( Reader) - READ 101
import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.reader(f)
It return the CSV object in “data”
for record in data:
print(record)
f.close()
['Rollno', 'name', 'class', 'stream', 'agg', 'percenrage', 'result']
['1', 'ramji', '12B', 'SCIENCE', '484', '96.8', 'PASS']
['2', 'anuj', '11A', 'COMM', '452', '90.4', 'PASS']
['3', 'ujjwal', '12C', 'HUMAN', '385', '77', 'PASS']
['4', 'shlok', '11B', 'SCIENCE', '490', '98', 'PASS']
['5', 'nipun', '11A', 'COMM', '347', '69.4', 'PASS']
……..
['10', 'harsh', '11C', 'HUMAN', '455', '91', 'PASS']
File Handling – (CSV)- DictWriter - WRITE 102
rollno,name,stream,fees
import csv 12,surendra,Humanities,2356
13,Ashok,Humanities,2356
headers =['rollno','name','stream','fees'] 15,Nipun,Humanities,2356
records = [ 22,Ayush Negi,Science,2356
{'fees': 2356, 'rollno': 12, 'name': 'surendra', 'stream': 'Humanities’},
{'rollno': 13, 'stream': 'Humanities', 'fees': 2356,'name': 'Ashok’},
{'rollno':15,'name':'Nipun','stream':'Humanities','fees':2356},
{'rollno': 22, 'name': 'Ayush Negi', 'fees': 2356,'stream': 'Science’},
]
f = open("student.csv", "w")
writer = csv.DictWriter(f, fieldnames = headers, lineterminator='\n')
writer.writeheader()
writer.writerows(records) Fieldnames is compulsory
f.close()
print("Check your file now....“)
Writeheader() method is compulsory
File handling - CSV(DictReader)- READ 103
import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.DictReader(f)
for record in data:
print(dict(record))
f.close()
OrderedDict([('Rollno', '1'), ('name', 'ramji'), ('class', '12B'), ('stream', 'SCIENCE'), ('agg', '484'), ('percenrage', '96.8'), ('result',
'PASS')])
OrderedDict([('Rollno', '2'), ('name', 'anuj'), ('class', '11A'), ('stream', 'COMM'), ('agg', '452'), ('percenrage', '90.4'), ('result', 'PASS')])
OrderedDict([('Rollno', '3'), ('name', 'ujjwal'), ('class', '12C'), ('stream', 'HUMAN'), ('agg', '385'), ('percenrage', '77'), ('result', 'PASS')])
OrderedDict([('Rollno', '4'), ('name', 'shlok'), ('class', '11B'), ('stream', 'SCIENCE'), ('agg', '490'), ('percenrage', '98'), ('result', 'PASS')])
OrderedDict([('Rollno', '5'), ('name', 'nipun'), ('class', '11A'), ('stream', 'COMM'), ('agg', '347'), ('percenrage', '69.4'), ('result', 'PASS')])
OrderedDict([('Rollno', '8'), ('name', 'sehaj'), ('class', '12A'), ('stream', 'SCIENCE'), ('agg', '421'), ('percenrage', '84.2'), ('ressult',
'PASS')])ult', 'PASS')]) ', 'PASS')])
OrderedDict([('Rollno', '9'), ('name', 'swarnima'), ('class', '12A'), ('stream', 'SCIENCE'), ('agg', '345'), ('percenrage', '69'), ('result',
'PASS')])
OrderedDict([('Rollno', '10'), ('name', 'harsh'), ('class', '11C'), ('stream', 'HUMAN'), ('agg', '455'), ('percenrage', '91'), ('result', 'PASS')])
DictReader() method read all the CSV data in Ordered Dictionary format.
File handling - CSV(DictReader)- READ 104
import csv
f = open(r"C:\Users\geetanjali\Desktop\student.csv", "r")
data = csv.DictReader(f) DictReader() method is used to read data as a
for record in data: Dictionary
print(dict(record))
f.close()
{'Rollno': '1', 'name': 'ramji', 'class': '12B', 'stream': 'SCIENCE', 'agg': '484', 'percenrage': '96.8', 'result': 'PASS'}
{'Rollno': '2', 'name': 'anuj', 'class': '11A', 'stream': 'COMM', 'agg': '452', 'percenrage': '90.4', 'result': 'PASS'}
{'Rollno': '3', 'name': 'ujjwal', 'class': '12C', 'stream': 'HUMAN', 'agg': '385', 'percenrage': '77', 'result': 'PASS'}
{'Rollno': '4', 'name': 'shlok', 'class': '11B', 'stream': 'SCIENCE', 'agg': '490', 'percenrage': '98', 'result': 'PASS'}
{'Rollno': '5', 'name': 'nipun', 'class': '11A', 'stream': 'COMM', 'agg': '347', 'percenrage': '69.4', 'result': 'PASS'}
…..
{'Rollno': '10', 'name': 'harsh', 'class': '11C', 'stream': 'HUMAN', 'agg': '455', 'percenrage': '91', 'result': 'PASS'}
Ordered Dictionary is not in our syllabus thus we change them into normal dictionary using
dict(record)
Sample code (csv file writing)
csv file
Output Structure
Sample Code(csv file Reading)
Sample code for Searching)
Searching a record in csv file
File handling –CSV ( Search Record) 111
import csv
name = input('Name to Search :')
Name to Search :Ashok
Ashok found in CSV file..
file = open('student.csv','r')
reader = csv.DictReader(file)
found =0
for x in reader: Name to Search :nipun
x = dict(x) nipun not found....
if(x['name']==name):
print(name,' found in CSV file..')
found =1
file.close()
if(found == 0):
print(name, ' not found....')
File Handling- CSV ( Delete Record ) 112
import csv
name = input('Name to delete :')
records=[]
found =0
file = open("student.csv","r")
reader = csv.DictReader(file)
for record in reader:
record = dict(record)
if(record['name']!=name): Collect all record in a list excluding the matched one
records.append(dict(record))
else:
found =1
file.close() Headers are not the part of DictReader ()
# Remove the old file and create a new csv file
headers=['rollno','name','stream','fees']
file = open("student.csv","w")
writer = csv.DictWriter(file,fieldnames =headers, lineterminator ='\n')
writer.writeheader()
writer.writerows(records)
file.close()
if(found==0):
print(name, " does not exists") Write all the collected record in the same CSV file
else:
print(name," deleted successfully")
File Handling (CSV) UPDATE RECORD 113
import csv
name = input('Name to Update :')
records = []
found = 0
file = open("student.csv", "r")
reader = csv.DictReader(file) Ask for a new Name when Name match,
for record in reader:
record = dict(record) append the list in both cases
if(record['name'] == name):
record = dict(record)
record['name'] =input('New Name:')
records.append(record)
found=1
else:
records.append(dict(record))
file.close()
headers = ['rollno', 'name', 'stream', 'fees']
file = open("student.csv", "w") # Remove the old file and create a new csv file
writer = csv.DictWriter(file, fieldnames=headers, lineterminator='\n')
writer.writeheader()
writer.writerows(records)
file.close()
if(found == 0):
print(name, " does not exists")
else:
print(name, " updated successfully")
SAMPLE BOARD QUESTIONS ??
Fileout=open(“student.txt”, ”w”)
for i in range(3):
name=input(“enter name of student:”)
Fileout.write(name)
Fileout.write(‘\n’)
Fileout.close()
file = open(r"abcd.txt",'r')
count=0;
for line in file.readlines():
if line[0]=='T':
count+=1
file.close()
print("Total lines that start with alphabet 'T' :",count)
program to find out the total number of words in any given test file
program to find out the total number of words in any given test file
file = open(r"abcd.txt")
words = lines = 0
for line in file.readlines():
lines += 1
words += len(line.split())
file.close()
print("Total Words in this File :", words)
print("Total Lines in this File :", lines)
WAP to print just the last line of a text file “data.txt”
WAP to print just the last line of a text file “data.txt”
Fin=open(“data.txt”, “r”)
Linelst=Fin.readlines()
print(“Last line=“,Linelst[-1])
WAP to read the text file and prints only the numbers or digits from the file.
WAP to read the text file and prints only the numbers or digits
from the file.
F=open(“an.txt”,”r”)
for line in F :
words=line.split()
for i in words :
for letter in i:
if(letter.isdigit())
print(letter)
WAP that copies a text file “source.txt” onto “target.txt” barring
the lines starting with a “@” sign
WAP that copies a text file “source.txt” onto “target.txt”
barring the lines starting with a “@” sign