File Handling
File Handling
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.
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
Read a file
f = open("demofile.txt", "r")
print(f.read())
output
Readline
f = open("demofile.txt", "r")
print(f.readline())
output
program
f = open("demofile2.txt", "a")
f.close()
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()
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")