Python Basics

Python File Handling

File operations

Python File Handling

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.

File Open

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.

f = open("demofile.txt", "r")
print(f.read())

Read Files

Assume we have the following file, located in the same folder as Python: demofile.txt

f = open("demofile.txt", "r")
print(f.read())

Read only parts of the file:

f = open("demofile.txt", "r")
print(f.read(5))  # Returns the first 5 characters

Write/Create Files

To write to an existing file, you must add a parameter to the open() function:

  • "a" - Append - will append to the end of the file
  • "w" - Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Delete Files

To delete a file, you must import the OS module, and run its os.remove() function:

import os
os.remove("demofile.txt")

Tip: Always close files after you are done with them to free up system resources.