Friday, 31 October 2014

Files in Python eg

import os
import tempfile
strPath= "C:\New folder\Testing.txt"
x1 = open(strPath, "r+")
print x1.readlines()    # Read All the lines...
print "Where is the file pointer: ", x1.tell()
x1.seek(5)  # Place the control at 5th character..
print "Control is placed at first character: ", x1.read(1)
print "Where is the file pointer: ", x1.tell()

x1.seek(0)
print "printing lines"
l1= []  #Declare an empty List
for line in x1:
    print len(str(line).strip()) , ": and line text: ", line

print"+++++++++++Read line by line++++++++++++++++++"
x1.seek(0)
while True:
    li= x1.readline()
    if not li: break
    print li
print"+++++++++++++++++++++++++++++"
x1.close()

print os.getcwd()

try:
    cf= open("C:\New folder\Testing1.txt", "w+")
    cf.write("THis is my text")
    filePos= cf.tell()
    print "File pointer positioned at: ", filePos
    cf.seek(0)
   
    print cf.readlines()
    cf.close()
except Exception, e:
    print e
else: print "File created.."


try:
    af= open("C:\New folder\Testing1.txt", "a+")
#     af.append("Second line data")
    af.writelines("\nHello")  
    af.close()
except Exception, e:
    print e
finally:
    pass

dat1= "Second line data"

f1 = open("C:\New folder\Testing1.txt","a") ## file open in appending mode i.e 'a'  
f1.writelines("\n" +dat1)

f1.close()


print tempfile.mkstemp(".txt", "test", "" , True )
print tempfile.gettempdir()
print tempfile.tempdir


No comments:

Post a Comment