File handling
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
file Handling
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains
some data, then it will be overridden but if the file is not present then it
creates the file as well.
3. a: open an existing file for append operation. It won’t override existing
data.
4. r+: To read and write data into the file. The previous data in the file will
be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Open a file
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Read a file
f = open("demofile.txt", "r")
print(f.read())
output
Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Readline
f = open("demofile.txt", "r")
print(f.readline())
output
Hello! Welcome to demofile.txt
write to an Existing 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
program
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
output:
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the overwriting:
f = open("demofile3.txt", "r")
print(f.read())
output
Woops! I have deleted the content!
Delete a file
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
import os
os.remove("demofile.txt")