Java, .NET, PHP, PYTHON, ANGULAR, .NET, ML, Data Scince, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

File Handling Operation in Python:-


File is a collection of records ,if we want to store program output permanently under computer hard disc then we can use file handling operation.

File handling provide multiple operation on file


Python Provide predefined method to manage file handling operation.

1 open()  :-  using this method we can open file for operation ,if file not exist then it will create file .

  f = open("filename",mode)    # w for write ,r for read ,w+ for write|read,r+ for read|write,a for append

2 write()  :-  this method is used to write content into file.

f.write(data)

code for write

f = open("student.txt","w")
f.write("student information")
f.close()

3 read()

f = open("student.txt","r")
s=f.read()
print(s)
f.close()


  s = f.read()
  print(s)



..................................................................................................................

4 append file:-

f = open("student.txt","a")
s = input("write content")
f.write(s)

f.close()

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Program of file handling using class and object:-

class FileOperation:
    def createFile(self):
       self.f = open("info.txt","a+")
    def writeFile(self):
      title = input("Enter title")
      self.f.write("\n"+title)
      desc = input("Write content")
      self.f.write("\n"+desc)
    def readFile(self):
      self.f.seek(0)  #it will reset cursor position to any index
      res = self.f.read()
      print(res)
      self.f.close()

obj = FileOperation()
obj.createFile()
obj.writeFile()
obj.readFile()



Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post