File Methods

Last Updated : 5th September 2025


In Python, files have several methods that allow you to perform various operations on the file.

  • read(): Reads the entire content of the file and returns it as a string.
  • readline(): Reads a single line from the file and returns it as a string.
  • readlines(): Reads all the lines of the file and returns them as a list of strings.
  • write(): Writes the given content to the file.
  • writelines(): Writes a list of strings to the file.
  • close(): Closes the file.
  • flush(): Flushes the file buffer.

    We cover already in previous section

  • tell(): Returns the current position of the file pointer.
file = open("example.txt", "r")
position = file.tell()
print(position)

content = file.read()
print(content)

position = file.tell()
print(position)
file.close()
  • seek(): Moves the file pointer to a specific position in the file.
file = open("example.txt", "r")
content = file.read()
print(content)

file.seek(0)
content = file.read()
print(content)
with open("data.txt", "r") as f:
    print(f.read(5))       # first 5 chars
    print(f.tell())        # position
    f.seek(0)              # reset pointer
    print(f.read(5))       # again first 5 chars
  • readable(): Returns True if the file is readable, False otherwise.
  • writable(): Returns True if the file is writable, False otherwise.
  • closed(): Returns True if the file is closed, False otherwise.
  • seekable(): Returns True if the file is seekable, False otherwise.

💡 Quick Practice