Files

Files are named locations on the computer’s disk that permanently store information for future use of its data. They are used to permanently store data in non-volatile memory (e.g. hard disk) as opposed to volatile sources like Random Access Memory RAM, which loses its data when the computer is turned off.

File Handling

Handling files is a common feature that many languages use to work with the computer’s file system. In Python, file handling is possible and usually takes place in the following order:

  1. Open (or create) the file.
  2. Perform operations on the file, such as reading or writing to it.
  3. Close the file to its resources are freed.

Example

The small example below demonstrates how one process of file handling could work:

# Create, or overwrite, a file and open for writing
file = open("myfile.txt", "w")
file.write("Hello world!")
file.close()
# Open existing file to read and print text content
file = open("myfile.txt", "r")
first_two_bytes = file.read(2)
next_three_bytes = file.read(3)
the_rest = file.read()
print(first_two_bytes, next_three_bytes, the_rest, sep="\n")
file.close()

In the first part of the code example, a plain text file named myfile.txt was created and opened in the "w" “write”-mode. Then a piece of text was written to the file and closed afterward.

In the next part, a few calls to the .read() method are assigned to some variables and then each one is printed on a new line:

He
llo
world!

More information about file methods in Python can be found below.

Files

.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.
.remove()
Allows the user to delete a file if it exists.
.rmdir()
Allows the user to delete a folder if it exists.
.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.
.unlink()
Allows the user to delete a file path if it exists.
.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