Professional Documents
Culture Documents
mode description
r Read or input
When you want to read a file, get data from the
file
w Write or output
When you want to write in file, put data in the
file
r+ Read as well write
When you want to overwrite
NO new data will be added
Size of file will remains the same
w+ Write then read
Creates the file, erase the previous data write
new data then read
a Append
Add at the end
a+ Append and read
Previous data can be read, new will be added,
no overwriting
F1=open(“abc.txt”,”r+”)
File object F1
Name of file on disk is “abc.txt”
Mode of the File object r+ or rewrite
File=open(“story.txt”,”w”)
File object File
File name “story.txt”
Mode of file object w or write
Remember:
Mode is for File Object not FILE
When I say file object is a read object, what does this mean?
Ans
We can give the command to read through this file object
ONLY
1. Absolute referencing
- Start from the drive
- Then root
- Then folder
- Then the file name
Program1.py absolute path
C:\\flutter\\bin\\b1\\program1.py
print("c:\futter\bin\bin1\program1.py")
c:utterinin1\program1.py
>>> print("c:\\futter\\bin\\bin1\\program1.py")
c:\futter\bin\bin1\program1.py
>>> print(r"c:\futter\bin\bin1\program1.py")
c:\futter\bin\bin1\program1.py
Raw string - without formatting
Use r in print
print(r” “)
Example
>>> print("hello\nfriends")
hello
friends
>>> print(r"hello\nfriends")
hello\nfriends
Format string
- Use f
print(f”the name is {name} and address is {address}”)
- Use format
>>> print("value of a is {1} and value of b is
{0}".format(a,b))
value of a is 900 and value of b is 90
- Use %
>>> a=90
>>> b=900
>>> print("value of a is %s and value of b is %s"%(a,b))
value of a is 90 and value of b is 900
>>> print("value of a is %s and value of b is %s"%(b,a))
value of a is 900 and value of b is 90
Let’s assume there is a file project.py under examples folder
C:\\Python\\examples\\project.py
2. Relative referencing
- CWD or current working folder
- Start the folder below the Current working folder
Let’s program2.py and CWD is flutter
bin\\b1\\program2.py
..bin\\b1\\program2.py
Lets CWD is Python and I want open a file “a.txt” in the lib
folder
Absolute path Relative path
c:\\python\\lib\\a.txt lib\\a.txt
Let’s CWD Python you want open a file “story.txt” in bin of
flutter folder
Absolute path Relative path
c:\\flutter\\bin\\story.txt As bin in not under my CWD
so relative path is not
possible
Let’s CWD B1 and want to open a file “one.txt” in B2 folder
Absolute path Relative path
c:\\flutter\\bin\\b2\\one.txt Not possible because B2 is
not used B1
Let’s CWD is B1 and want to open a file “a1.txt” in bin folder
Absolute path Relative path
c:\\flutter\\bin\\a1.txt Not possible , bin folder is
above B1( bin is parent of
B1)
write()
File handler.write(string)
File=open("student.txt","w")
x=int(input("Enter number of students:"))
for i in range(x):
n=input("Enter the name :")
File.write(n+"\n")
File.close()
File.write(n)
File.write(“\n”)
File=open("student.txt","w")
x=int(input("Enter number of students:"))
rec="Rollno\tName\t\tMarks\n"
File.write(rec)
for i in range(x):
r=int(input("Enter Rollno:"))
File.write(str(r)+"\t")
n=input("Enter the name :")
File.write(n+"\t\t")
m=float(input("Enter Marks"))
File.write(str(m)+"\n")
File.close()
Writelines()
File=open("student.txt","w")
x=int(input("Enter number of students:"))
l=[]
for i in range(x):
n=input("Enter the name :")
l.append(n+"\n") #\n just for new line
File.writelines(l) #outside the loop
File.close()
File=open("student.txt","w") # “a” for append
x=int(input("Enter number of students:"))
rec="Rollno\tName\t\tMarks\n"
l=[]
l.append(rec)
for i in range(x):
r=int(input("Enter Rollno:"))
n=input("Enter the name :")
m=float(input("Enter Marks"))
rec=str(r)+"\t"+n+"\t"+str(m)+"\n"
l.append(rec)
File.writelines(l) #will write each string in the list as a line
File.close()
Writelines cannot print “\n” on its own
“\n” should be there in string
Q if my file contains
ABCDEFGHIJK
I open my file in “r” mode
A=File.read(5) # ABCDE
B=File.read(4) #FGHI
C=File.read(3) #jk\n
print(A)
print(B)
print(C)
Is this program correct, if yes, what will be the output?
Q if my file contains
ABCDEFGHIJK
I open my file in “r” mode
File=open(“a.txt”,”r”)
A=File.read(5)
while True:
str=File.readline()
if str==’’: #no space in between quotes
Break
print(str)
\n after the line in the file and \n in print()
print(str,end=””) # reduce one \n
3. readlines() → returns all the lines in the form of list of
strings
File=open("a11.txt","r")
s=File.readlines()
for x in s:
print(x)
File.close()
File=open("a11.txt","r")
S=File.readlines()
for x in S:
print(x)
Method of reading character by character
Question
Q1 Write a program in Python to display number upper
and lower characters from the file “abc.txt”
Solution
- Open the file read mode
- Read using read(), readline(),readlines() to process
character by character
- For counting declare a variable outside the loop initialize
with 0 before starting the loop
- Loop
- Check and increment
- Print the value of count outside the loop after processing
def count_upper_lowercase():
File=open("a11.txt","r")
data=File.read() # split into character
count_u=0
count_l=0
for a in data:
if a in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
#a.isupper()
count_u+=1
elif a.islower(): #"a"<=a<="z"
count_l+=1
print("Number of upper case ",count_u)
print("Number of lower case ",count_l)
File.close()
def count_words1():
File=open("a11.txt","r")
data=File.read() # split into character
count_s=0
for a in data:
if a==" " or a=="\n":
count_s+=1
print("Number of words ",count_s)
File.close()
def count_words2():
File=open("a11.txt","r")
data=File.read().split() # split into character
l=len(data)
print("number of words ",l)
File.close()
Q Write a program in Python to display all the words that ends with a
vowels
Ans
S=File.readlines()
for a in S:
for x in a:
if x[-1] in 'AEIOUaeiou':
print(x)
print("number of lines",c)
With in Python
With statement → program code will be easier and compact
with statement as Filehandlername:
statement(s)
No need to give close
With closes automatically
with open(“a11.txt”,”r”) as F:
while True:
s=F.readline()
if s==””:
Break
print(s)
Single line opening and closing the file
with open(“ax.txt”,”w”) as File:
for a in range(10):
s=input(“enter the line”)
File.writeline(s+”\n”)
NOTE: if mode is not specified at the time of opening
the file it will open in read “r” mode.
File=open(“a.txt”)
This means the file is opened in read mode
-
- What is the advantage of exception handling?
Ans:
1. Eliminates runtime error
2. Behaves like a normal program
Exceptions in Python
1. ZeroDivisionError - when you divide a number by 0
ZeroDivisionError: division by zero
2. ValueError- when the conversion is not possible
ValueError: invalid literal for int() with base 10: 'a12'
c=a//b
print(c)
except ZeroDivisionError:
print("error in input")
except ValueError:
print("cannot divide by this")
except FloatingPointError:
print("floating point")
except TypeError:
try:
Fname=input("enter the filename:")
F=open(Fname,"r")
print("file opened")
except FileNotFoundError:
print("please check")
Method 1:
Try -- except to read a binary file
#WAP to accept name and find if the student is in the class or not
def findall():
File=open("student.dat","rb")
L=[]
count=0
name=input("Enter name to search:")
try:
while True:
L=pickle.load(File)
def findall1():
File=open("student.dat","rb")
L=[]
count=0
name=input("Enter name to search:")
try:
while True:
L=pickle.load(File)
findall1()
#rollno,name,age
import pickle
import os
L=[]
F1=open("Student.dat","rb")
F2=open("Temp.dat","wb")
roll=int(input("Enter roll no for deletion:"))
try:
while True:
L=pickle.load(F1)
if L[0]!=roll: # execpt this rollno write in the temperorary file
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("Student.dat")
os.rename("Temp.dat","Student.dat")
Modify File
1. Using Temporary file
2. Without using temporary file
Using Temporary file
Algorithm
Step 1: open source file read mode
Step 2: open a temporary file in write mode
Step 3: Accept data for modification
Step 4: read the file
Step 5: if data match with data to modify: write modified value
Else: write the original data in temporary file
If you are writing algorithm of delete:
If data matches with data to delete: pass else: write in the
temporary file or If data does not matches with data to delete:
write in the temporary file
Step 6: repeat the process till end of file
Step 7: close both the files
Step 8: remove original file
Step 9: rename temporary file as original file
Step 10: stop
Selected records to be modified:
def Modify():
F1=open("student.dat","rb")
F2=open("temp.dat","wb")
R=int(input("Enter Rollno to modify"))
N=input("Enter new name:")
M=float(input("Enter the modified marks"))
L=[]
try:
while True:
L=pickle.load(F1)
if L[0]==R:
L[1]=N
L[2]=M
pickle.dump(L,F2)
else:
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("student.dat")
os.rename("temp.dat","student.dat")
L=[]
try:
while True:
L=pickle.load(F1)
print("Rollno=",L[0],"\tName=",L[1])
M=float(input("Enter the modified marks"))
L[2]=M
pickle.dump(L,F2)
except EOFError:
F1.close()
F2.close()
os.remove("student.dat")
os.rename("temp.dat","student.dat")
Python manages the file pointer and this file pointer can
processed in Python program
To process the File pointer
1. seek() → places the file pointer
2. tell() → tells the position of file pointer
tell()
- No parameter
- Fileobject.tell()
- File pointer starts from 0
- When you open a file in “r”, “w” mode file pointer is on 0th
byte, in “a” then it is at the end after the last byte
-
>>> F=open("a11.txt","r")
>>> D=F.read(10)
>>> print(D)
Pineapple
>>> print(F.tell())
10
>>> D=F.read(5)
>>> print(F.tell())
15
>>> F=open("abcd.txt","w")
>>> F.write("ABCDE")
5
>>> print(F.tell())
5
>>> F.close()
>>> F=open("abcd.txt","a") #places the pointer after the last byte
>>> print(F.tell())
5
>>> F.write("HIJ")
3
>>> print(F.tell())
8
>>> F=open("abcd.txt","w") #places the pointer on 0 byte
>>> print(F.tell())
0
>>> F.write("HIJ")
3
>>> print(F.tell())
3
seek ()
- Places the file pointer
- File opened r, r+,w+ any mode
Syntax
Example
File.seek(10) Place on the pointer on 10(11th ) byte
File.seek(10,0) same
File.seek(-5,1) left by 5 bytes from current position
File.seek(5,1) right by 5 bytes from current position
File.seek(-5,2) right by 5 byte from last byte
file.seek(0,2) places the pointer on the last byte
Remember:
1. From BOF(0th byte) you cannot go back (can’t go towards
left) → negative values is not allowed
File.seek(-5,0)
Is WRONG
2. From EOF(last byte) you cannot go further( can’t go towards
right) → positive values is not allowed
File.seek(5,2)
Is WRONG
3. But from current go back or further → negative and positive
both are allowed depending upon the direction
File.seek(1,1)
File.seek(-1,1)
Both are CORRECT
Eg
WAP to read last 10 byte of “abc.txt”)
File=open(“abc.txt”,”r”)
File.seek(-10,2)
D=File.read()
print(D)
File.close()
How Python read
def Modify():
File=open("student.dat","rb+")
L=[]
rollno=int(input("Enter rollno to modify"))
try:
while True:
t=File.tell() #track position before load
L=pickle.load(File)
if rollno==L[0]:
print("Name:",L[1],"\t previous marks=",L[2])
m=float(input("Enter new marks"))
File.seek(t)# seek the position before dump
L[2]=m
pickle.dump(L,File)
break
except EOFError:
print("No such Rollno")
File.close()
CSV File
- Data is separated by a comma(,)
- Used to store huge amounts of data
- By default the separator is comma, default delimiter
- You can the separator
- To process a csv file read in text → split to break into
different field
- Easier method of using csv module
- import csv
File open
open() function is used to open a CSV file
F=open(“s.csv”,”w”)
Remember
You will not write b as it is not a binary file
File close
Using close() function
#using writerows()
def create2():
File=open("emp.csv","w",newline="\n")
rep='y'
cwriter=csv.writer(File,delimiter=",")
cwriter.writerow(["Empno","Name","Job","Salary"]) #header of the
csv file
L=[]
while rep in "Yy":
empno=int(input("Enter employee number:"))
name=input("Enter name:")
job=input("Enter Job:")
salary=float(input("Enter salary:"))
L.append([empno,name,job,salary])
rep=input("Want to add more:")
cwriter.writerows(L)
File.close()
def append():
File=open("emp.csv","a",newline="\n")
rep='y'
cwriter=csv.writer(File,delimiter=",")
# no need to give head as the header is already there
while rep in "Yy":
empno=int(input("Enter employee number:"))
name=input("Enter name:")
job=input("Enter Job:")
salary=float(input("Enter salary:"))
L=[empno,name,job,salary]
cwriter.writerow(L)
rep=input("Want to add more:")
File.close()
append()
import csv
def readall1():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
print(d)
File.close()
def readall2():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
for d in creader:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
File.close()
def readall3():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
elif float(d[3])>2500:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
count+=1
File.close()
def readall4():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
elif d[2]=='A':
print("{0:10}{1:20}{2:20}{3:10}".format(d[0],d[1],d[2],d[3]))
count+=1
File.close()
readall4()
Calculate and display the annual salary
def readall3():
File=open("emp.csv","r",newline="\n")
rep='y'
creader=csv.reader(File,delimiter=",")
count=0
for d in creader:
if count==0:
print("{0:10}{1:20}{2:20}{3:10}{4:20}".format(d[0],d[1],d[2],d[3],"Ann
ual Salary"))
elif float(d[3])>2500:
print("{0:10}{1:20}{2:20}{3:10}{4:10}".format(d[0],d[1],d[2],d[3],float
(d[3])*12))
count+=1
File.close()