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

.close()
Allows the user to close an open file within the IDE.
.read()
Allows the user to read the contents of an open file.
.readline()
Returns the first line of content from an open file.
.seek()
Allows the user to move the location of the file handle's reference point within an open file from one place to another.
.truncate()
Allows the user to resize the file to a given number of bytes when the file is accessed through the append mode.
.writable()
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.
.write()
Allows the user to add additional text to a file when the file is opened in append mode.
Edit this page on GitHub

Contributors

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

Learn Python on Codecademy

Edit this page on GitHub

Contributors