Python- File Handling Examples




>>>fdesc= open(“data.txt”,”w”)  #will create data.txt
>>>fdesc
>.>> for count in range(0,100)# to write 1 to 100 in file
>>>.      fdesc.write(str(count)+”\n”)

>>> fdesc.close()


>>> Cat data.txt
Now to append 100 to 199

>>>fdesc= open(“data.txt”,”a”)
>>>fdesc
>.>> for count in range(100,200)# to append100 to 200 in file
>>>.      fdesc.write(str(count)+”\n”)

>>> fdesc.close()


>>> Cat data.txt


To read data from file

>>>fdesc = open(“data.txt”)

>>> for line in fdesc.readlines():
>>>.       Print line.strip() # strip adds \n

>>> fdesc.close()

filehandling.py
#!/usr/bin/python

fdesc=open("data.txt","r")
#fdesc.write("world")
print fdesc.read()
fdesc.close()




Replace, rename

>>> Import. os
>>> os.rename(“data.txt”,”record.txt”)
>>>ls #To check at command promt


Filehandling.py

#!/usr/bin/python

import os

os.rename("data.txt","test2.txt")




Try os.delete()


os MORE FUNCTIONS IN aSSIGNMENT


Reactions: