File handling in Python

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()
File Append File Write
Your Rating




Post your comments , suggestion , error , requirements etc here




HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer