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
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 |
t | Text mode ( default ) |
b | Binary Mode |
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.
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
rb
: Read Binary ( mode )
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob1.jpg','rb')
blob_data=fob.read()
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 ) fob= open(path,'r',encoding='utf8',errors='ignore')
Moving the file position by seek()
We can read the file position by tell()
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.