Mode of file opening
Mode | Details |
r | Read only ( if file exist) , no file is created |
w | Write file, file is created if not available. Over written if file already exist. |
x | Create file if not exit. Return error if file is already available. |
a | Append file ,file is created if not exists |
Mode of handling the file
t | Text mode ( default ) |
b | Binary Mode |
Reading file, our built-in function open()
will return one file object fob
For all these examples we created one data.txt file with four lines of text. You can create your file and keep in the same folder having your python files.
fob=open('data.txt','r')
print(fob.read())
This will print the total content of our file data.txt
This is first line
This is second line
This is third line
This is fourth line
We can read part of the file by giving input parameter.
fob=open('data.txt','r')
print(fob.read(10))
10 chars are printed
This is fi
Reading Binary data
rb
: Read Binary ( mode )
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob1.jpg','rb')
blob_data=fob.read()
Reading a line by using readline()
fob=open('data.txt','r')
print(fob.readline())
Output is here , prints the first line.
This is first line
By using the print command again we can print second line as the file pointer moves to next line after printing first line
fob=open('data.txt','r')
print(fob.readline())
print(fob.readline())
Output will give us first two lines.
This is first line
This is second line
Reading every line till end
fob=open('data.txt','r')
for i in fob:
print(i)
Output is here
This is first line
This is second line
This is third line
This is fourth line
It is a good idea to close file object at the end
fob=open('data.txt','r')
for i in fob:
print(i)
fob.close()
mode='x' will generate error if file is already available. It will create a new file and add data.
fob=open('data4.txt','x')
fob.write("Hello")
fob.close()
fob=open('data4.txt','r')
print(fob.readline()) # Hello
fob.close()
Getting the mode of file object
print(fob.mode)
Output is mode used while creating the file object ( r, w, a , x )
Moving the file position by seek() »
We can read the file position by tell() »
« File Append
File Write »
← Subscribe to our YouTube Channel here