File Handling In Python
Python File Handling: Comprehensive Theory
File handling is an essential part of any web application or software. It allows you to create, read, update, and delete files on the server or local system.
Python has several functions for creating, reading, updating, and deleting files.
open()
The key function for working with files in Python is the open() function.
The open() function takes two parameters: filename and mode.
File Modes
There are four different methods (modes) for opening a file:
| Mode | Description | behavior |
| :--- | :--- | :--- |
| "r" | Read | Default value. Opens a file for reading, error if the file does not exist. |
| "a" | Append | Opens a file for appending, creates the file if it does not exist. |
| "w" | Write | Opens a file for writing, creates the file if it does not exist. Overwrites existing content. |
| "x" | Create | Creates the specified file, returns an error if the file exists. |
In addition, you can specify if the file should be handled as binary or text mode:
| Mode | Description |
| :--- | :--- |
| "t" | Text - Default value. Text mode. |
| "b" | Binary - Binary mode (e.g. images). |
Syntax:
f = open("demofile.txt")
# is the same as:
f = open("demofile.txt", "rt")
2. Reading a File
To read the content of a file, we use the read() method.
f = open("demofile.txt", "r")
print(f.read())
f.close()
Reading Parts of the File
You can also specify how many characters you want to return:
f = open("demofile.txt", "r")
print(f.read(5)) # Reads first 5 characters
Reading Lines
readline(): Returns one line.readlines(): Returns a list containing each line in the file as a list item.
f = open("demofile.txt", "r")
print(f.readline()) # Reads the first line
3. Writing to a File
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()
with
The best practice for opening files in Python is using the with statement. It automatically closes the file for you, even if an exception occurs.
with open("demofile.txt", "r") as f:
content = f.read()
print(content)
# No need to call f.close()
5. Deleting a File
To delete a file, you must import the os module and use its os.remove() function:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Summary Table
| Method | Description |
| :--- | :--- |
| close() | Closes the file. |
| read([n]) | Returns the file content. Optional n specifies characters to read. |
| readline() | Returns one line from the file. |
| readlines() | Returns a list of lines from the file. |
| write(string) | Writes a string to the file. |
| writelines(list) | Writes a list of strings to the file. |
Practice Problems
- Read and Count: Write a Python program to read a file and count the number of lines in it.
- Copy Content: Write a script that reads content from
source.txtand writes it todestination.txt. - Append Input: Create a program that takes user input and appends it to an existing file named
notes.txt. - Safe Read: Write a function that tries to read a file but prints a friendly message if the file doesn't exist (Hint: Use
os.path.existsortry-except).