Python – File append

Previous
Next

Append mode(“a”) :         

  • Opens file in append mode.
  • If file is present, it will place the cursor at the end of existing data to add new contents.
  • If file is not present, it creates new file.
class Copy:
    src = None
    dest = None
    def main():
        try:
            Copy.src = open("./script.py" , "r")
            Copy.dest = open("./copy.txt" , "a")

            for line in Copy.src:
                Copy.dest.write(line)
            print("File copied")

        except Exception as e:
            print("Exception :", e)

        finally:
            if Copy.dest != None:
                Copy.dest.close()
            if Copy.src != None:
                Copy.src.close()
        return

Copy.main()

tell() : Method belongs to File object. It returns the current position (value) on the file.

seek(): Method belongs to File object. It is used to sets the cursor position to specific location.

class Source:
    file = None
    def main():
        try:
            Source.file = open("./script.py" , "r")
            data = Source.file.read()
            print(data)

            print("Cursor at : ",Source.file.tell())
            Source.file.seek(0)
            print("Cursor at : ",Source.file.tell())

            data = Source.file.read()
            print(data)

        finally:
            if Source.file != None:
                Source.file.close()
        return
Source.main()

readLine(): A pre-defined method belongs to file object. It will read the current line and returns as a String object.

class Source:
    file = None
    def main():
        try:
            Source.file = open("./script.py" , "r")
            line = Source.file.readline()
            print("First line is : %s" %line)

            Source.file.seek(0,0)
            line = Source.file.readline()
            print("Line is : %s" %line)

        finally:
            if Source.file != None:
                Source.file.close()
        return
Source.main()
Previous
Next

Add Comment

Courses Enquiry Form