File Methods

Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk).

Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them.

When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order:

  1. Open a file
  2. Read or write (perform operation)
  3. Close the file

File handling is an important part of any web application.

Python has a set of methods available for creating, reading, updating, and deleting files:

File Methods

Allows the user to close an open file within the IDE.
Allows the user to read the contents of an open file.
Returns the first line of content from an open file.
Allows the user to move the location of the file handle's reference point within an open file from one place to another.
Allows the user to resize the file to a given number of bytes when the file is accessed through the append mode.
Allows the user to check if a file is writable or not. The function will return True if the file is writable and accessed in append or write mode, and False if it was accessed in read mode.
Allows the user to add additional text to a file when the file is opened in append mode.
Edit this page on GitHub


Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Python on Codecademy

Edit this page on GitHub