File handling in Python

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 of file opening

ModeDetails
rRead only ( if file exist) , no file is created
wWrite file, file is created if not available. Over written if file already exist.
xCreate file if not exit. Return error if file is already available.
aAppend file ,file is created if not exists
Mode of handling the file
tText mode ( default )
bBinary 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. 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 )

Managing error and encoding while reading.
fob= open(path,'r',encoding='utf8',errors='ignore')
Moving the file position by seek() We can read the file position by tell()

File Append File Write
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer