File handling is an important part of any web application or data processing script. Python has several functions for creating, reading, updating, and deleting files.
1. open() function and File Modes
The key function for working with files in Python is the open() function.
It takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"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 (overwrites existing content), creates the file if it does not exist."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:
"t"- Text: Default value. Text mode."b"- Binary: Binary mode (e.g. images).
f = open("demofile.txt", "rt")
2. read() / readline() / readlines()
To read a file, use the read() method.
f = open("demofile.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how many characters you want to return: f.read(5).
Read Lines:
You can return one line by using the readline() method:
print(f.readline()) # Reads the first line
print(f.readline()) # Reads the second line
Alternatively, you can loop through the file line by line:
for x in f:
print(x)
3. write() / writelines()
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()
4. close() file
It is a good practice to always close the file when you are done with it to free up system resources.
f = open("demofile.txt", "r")
print(f.readline())
f.close()
5. with statement (Context Manager)
Closing files manually is prone to errors (e.g., if an exception occurs before close() is called).
The best practice in Python is to use the with statement. It automatically takes care of closing the file once the block of code is exited, even if an error occurs.
with open("demofile.txt", "r") as file:
content = file.read()
print(content)
# The file is automatically closed here
6. File pointers (seek(), tell())
When you read a file, Python uses a pointer to keep track of where it is in the file.
tell(): Returns the current position of the pointer.seek(offset): Moves the pointer to a specific byte position.
with open("demofile.txt", "r") as f:
f.seek(10) # Move to the 10th byte
print(f.read()) # Reads from byte 10 onwards
7. Delete file (os.remove())
To delete a file, you must import the OS module, and run its os.remove() function:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Discussion
Loading comments...