File handling in Python

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.
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 thrird 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 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 thrird 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
Your Rating




Post your comments , suggestion , error , requirements etc here




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