Python
Python
FILE MODES:
Mode Description
r Opens a file for reading only. The file pointer is placed at the beginning of the
file.This is the default mode.
rbOpens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode
r+Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
rb+Opens a file for both reading and writing in binary format. The file pointer
placed at the beginning of the file.
wOpens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
wbOpens a file for writing only in binary format. Overwrites the file if the file the file
exists. If does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for
reading and writing .
a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
abOpens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
a+Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.
file=open(“test.text”,”r+”)
Here is this statement we will open a file “test.txt” in reading and writing purpose. In above example .txt extension used
for identify the file as text file. It is not mandatory to specify file extension by default file when you open a file it open in
text type .But if you want to open a binary file extension we use for binary file is .dat is compulsory.
Another function to create or open a file is file().Its syntax and its usage is same as open() function.
close() function :
The close() function to close the file and free up system resources taken up by the open file. After calling f. close(),
attempts to use the file object will automatically fail. Python automatically close a file when the reference object of file is
reassigned to other file.It is good practice to use close() method to close a file.
Syntax:
Fileobject.close()
close() function breaks the link of file object and the file on disk.After closing file no task can be perform on file through
the file object.
f=open(“test.txt”)
print(“The name of the file is :”,f.name)
f.close()
Output
The name of the file is : test.txt
f=open(“test.txt”) output:
print(“File Name :”,f.name) File Name : test.txt
print(“File mode :”,f.mode) File mode : r
print(“Is File readable :”,f. readable) Is File readable : True
print(“Is File closed :”,f.close) Is File closed : False
f.close() Is File closed : True
print(“Is File closed :”,f.close)
Writing To File:
We can write character data into file by using the following two method:
1)write(str):write() method take a string as a parameter and write it in the file.While writing data into file add EOL
character at the end of line as ‘\n’ otherwise all the data shall be written in single line without changing line or one line
space. Text file are store character data only so if you want to write integer data into file convert it into string.
Syntax:fileobject.write(string)
#A program to write name, rollno and marks of student in file.
f=open("stu.txt","w")
f.write("ram\n")
rollno=int(input("enter a rollno"))
f.write(str(rollno))
marks=int(input("enter a marks"))
f.write(str(marks))
f.close()
After execute the code file is created and stored in memory you can open stu.txt through file menu open option and
check data stored in file or not.
Note:
In above example data present in the file shall be overwritten every time when we run this program.
2) writelines(sequence): For writing a string at a time we use write method it can not be use for writing list,tuple etc. into
file. Sequence data type including string can be written using writeline() method in file.
Syntax:
Fileobject.writelines(sequence)
#A program to write subject namein file.
f=open("sub.txt","w")
l=["computer science\n","physics\n","economics\n","biology\n"]
f.writelines(l)
f.close()
Note:
You must have to be noticed we have used closed() method with every program.If you don’t want to use close() there is
an alternative method can be used in program.
With statement:
Using with statement ensure that all the resources allocate with file are deallocated automatically once we stop using
file.In with statement its not required to close the file.
Syntax: with open() as fileobject:
#A program to illustrate with statement.
with open("test.txt","w") as f:
f.write("python \n")
f.write("is an easy \n")
f.write("language \n")
print("Is file closed",f.close())
0utput:
Is file closed None
After execute the program when you open text file. Content stored in text file “test.txt”:
python
is an easy
language
APPENDINE TO FILE:
Append means to add if you want to add more data to a file which already existing and has some data in it.In such case we
open a file in ‘a’mode.In this mode data is add into already existing file at the end of the file after previous data.
In python we use ‘a’ mode to open a file in append mode. This means that:
If the file is already exists data will add at the end of the file’s current content. If file does not exists , it will be
created and data will add.
Syntax: fileobject=open(“filename”,’a’)
#A program to add data in already existing file.
with open("test.txt","a") as f:
f.write("simple syntax of language\n")
f.write("make it an easy \n")
f.write("language \n")
Content stored in text file “test.txt” after append:
python
is an easy
language
simple syntax of language
make it an easy
language
READING FROM A FILE:
Python provide various method to read data from a file.We can read character data from file by using following read
method:
1)read( )-to read the entire data of the file in term of character string from top to end of file.
2)read(n) – This method reads n number of characters from the file, or if thenumber of character less then n it will
reads the entire file until end of file.
3) readline() – This method reads only one line as a string from the text file;starts reading from the top and including
the end of line charcter.
4) readlines() – This method reads entire line from the text file into a liststarts reading from the top and including the
end of line charcter and return a list of lines.
# A program to perform read and write operation in text file
f=open("test.txt","w")
f.write("I love car\n")
f.close()
f=open("test.txt","r")
r=f.read()
print("content stored in file",r)
f.close()
# A program to write multiple line and read data through readline() in text file
f=open("test.txt","w")
n=int(input("enter no of line you want to write in text file"))
for a in range(n):
str=input("enter string")
f.write(str)
f.write("\n")
f.close()
f=open("test.txt","r")
r=f.readline()
print("first line in file",r)
r1=f.readline()
print("second line in file",r1)
f.close()
Output:
enter no of line you want to write in text file3
enterstringhello user
enterstringu r working with
enterstringpython text file
first line in file hello user
second line in file u r working with
#Write a program to read lines from text file diary.txt. count and display those line which start from alphabet ‘P’
f=open("diary.txt","w")
n=int(input("enter no of line you want to write in text file"))
for a in range(n):
str=input("enter string")
f.write(str)
f.write("\n")
f.close()
count=0
for a in open("diary.txt","r"):
if a[0]=='P':
print("line starts from alphabet P is",a)
count=count+1
print("total number of line starts from p",count)
Output:
enter no of line you want to write in text file3
enterstringhello user
enterstringPython is an easy language
enterstringsimple syntax
line starts from alphabet P is Python is an easy language
total number of line starts from p 1
#write a program to read a text file and count word ‘is’ come how many time in file
f=open("diary.txt","r")
r=f.read()
x=r.split()
count=0
for a in x:
if a=='is':
count=count+1
print("is comes in file",count,”times”)
f.close()
Output:
is comes in file 1 times
#write a program to read a text file and count alphabet ‘s’ come how many time in file
f=open("diary.txt","r")
r=f.read()
count=0
for a in r:
if a=='s':
count=count+1
print("s comes in file",count,"times")
f.close()
Output:
s comes in file 5 times
Once data is stored using dump ,it can be used for reading. For reading data from a file, we have to use pickle.load() to
read the object from pickle file.
Syntax:
Object=Pickle.load(fileobject)
Program to read binary file emp.dat and display the details of those employee whose salary is more then 20000 binary
file emp.dat
import pickle
f=open("emp.dat","rb")
for a in range(2):
r=pickle.load(f)
if r[2]>20000:
print(r)
f.close()
Output:
['Aman', 102, 22000.0]
Write a program to copy lines starts from lowercase character into another file.
f1=open("para.txt","w")
long=" "
for a in open('test.txt'):
print(a)
if a[0].islower():
f1.write(a)
f1.close()
f1=open("para.txt","r")
b=f1.read()
print(b)
f1.close()
Output :
hello user
u r working with
python text file
hello user
u r working with
python text file
WAP to replace the word first character start from alphabet ‘k’ to ‘c’ in a file data.txt.
f1=open("data.txt","w")
n=int(input("enter number of line "))
for a in range(n):
str=input("enter line")
f1.write(str)
f1.write('\n')
f1.close()
f1=open("data.txt","r")
b=f1.read()
print("data store in original file",b)
s=' '
for i in b:
if i=='k':
s=s+'c‘ output: enter number of line 2
else: enter line I love kar
s=s+ienter line kar in red kolour
f1.close() data store in original file
f1=open("data.txt","w") I love kar
f1.write(s)kar in red kolour
f1.close() data store in file after change
f1=open("data.txt","r") I love car
b=f1.read() car in red colour
print("data store in file after change",b)
f1.close()
Write a program to find ,count and display four character word in text file.
f1=open("test.txt","r")
b=f1.read()
print("data store in original file",b)
x=b.split()
count=0
for i in x:
iflen(i)==4:
print(i)
count=count+1
print("total four character word in file",count)
f1.close()
Output:
data store in original file
hello user
u r working with
python text file
user
with
text
file
total four character word in file 4