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.

Python Basics — Knowledge Check

Check your understanding of this section. Results are not saved—refresh the page to start over.

1. Which statement best describes Python?
2. What is the output of: print(type([]))?
3. Which loop is best when you know how many iterations you need?
4. What does a dictionary store?
5. How do you handle exceptions in Python?
6. What does pip install do?