Python Codes for File Handling

#!/usr/bin/python
# Open already exixting file in the same directory for read operation.

fo = open(“gsm1.py”, “wb”)
print “Name of the file: “, fo.name
print “Closed or not : “, fo.closed
print “Opening mode : “, fo.mode
print “Softspace flag : “, fo.softspace


#!/usr/bin/python
# Open already exixting file in the same directory for read operation.
fo = open(“gsm1.txt”, “r+”)
print “Name of the file: “, fo.name
print “Closed or not : “, fo.closed
print “Opening mode : “, fo.mode
print “Softspace flag : “, fo.softspace
#Read file from starting for 100 characters, then tell current location of #pointer
fvar=fo.read(100)
print fvar
print “\nCursor location is    “, fo.tell()
#Reposition the file pointer to start and Read file from 10oth location from #starting for 50 characters
fo.seek(100,0)
print  fo.read(50)
print “\nCursor location is    “,fo.tell()
#Reposition the file pointer to current position and Read file from starting #for 50 characters
fo.seek(0,1)
print fo.read(50)
print “\nCursor location is    “,fo.tell()

fo.close()


#!/usr/bin/python
import os
#
# Open already exixting file  or create new filein the same directory
# for read and write operation.
# Learn file reading, writing  to a file, writing line by line to a file
#
fo = open(“gsm1.txt”, “a+”)
print “Name of the file: “, fo.name
print “Opening mode : “, fo.mode

#Reposition the file pointer to start and Read file from starting for 10 characters
fo.seek(0,0)
fo.write(“Adding line to file\n Add another line\n then one more\n”)

#Reposition the file pointer to current position and Read file from starting for 10 #characters
#.seek(0,1)
fo.write(“adding 2nd line\n”)
for i in range(5):
    fo.writelines(“\nadd extra lines “)
    
fo.seek(0,0)
print fo.read()

fo.close()


#!/usr/bin/python
import os
#
# Open already exixting file  or create new filein the same directory
# for read and write operation.
# Learn file reading, writing  to a file, writing line by line to a file
# learn rename and remove functions for a file
#

fo = open(“well.txt”, “a+”)
fo2 = open(“well2.txt”, “w+”)
print “Name of the file: “, fo.name
print “Opening mode : “, fo.mode

#Read file from starting for 100 characters
fvar=fo.read(100)
print fvar

fo.close()
fo2.close()

os.rename(“well.txt”,”well1.txt”)
os.remove(“well2.txt”)


#!/usr/bin/python
import os
#
# Open already exixting file for read operation reading file line by line.
#
fo = open(“gsm1.txt”, “r+”)
print “Name of the file: “, fo.name
print “Opening mode : “, fo.mode

#Read file from starting for 100 characters
for i in range(100):
    fvar=fo.readline()
    print “line = “, i, fvar
fo.close()