teach-ict.com logo

THE education site for computer science and ICT

3. Close File

Once the program has finished using the file, it has to be closed, otherwise it can't be used by other applications.

In Python, you close files using the close() method

Look at this example of Python code:

                  filehandle = open('mytextfile.txt', 'r')

First it opens a file called 'mytextfile.txt' in read mode.

As discussed on the previous page, it gives it the file handle "filehandle". Then it immediately closes the file.

In addition to allowing other programs to access the file, closing files is important because otherwise the file content may remain in RAM. Closing it frees up that memory to be used for something else.



Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Python command to close a file