Files
Opening and closing files
Files can be opened using the open()
function, which returns a file object.
It’s important to close files after use to free system resources.
We can open a file using the with
statement, similar to working with objects.
This ensures that the file remains open only within the indented block, and it is automatically closed afterward.
Permissions
Permission | Usage |
---|---|
r | for read only, with the pointer at the beginning of the file. It's the default |
r+ | for read and write, with the pointer at the beginning |
w | for write only, overwrites the file if it exists, else creates it |
w+ | for write and read, overwrites the file if it exists, else creates it |
a | for append, with the pointer at the end of the file. It creates a new file if it doesn't exist |
a+ | for append and read, with the pointer at the end of the file. It creates a new file if it doesn't exist |
rb | for read only in binary format, with the pointer at the beginning |
rb+ | for read and write in binary format, with the pointer at the beginning |
wb | for write only in binary format, overwrites the file if it exists, else creates it |
wb+ | for write and read in binary format, overwrites the file if it exists, else creates it |
ab | for append in binary format, with the pointer at the end of the file. It creates a new file if it doesn't exist |
ab+ | for append and read in binary format, with the pointer at the end of the file. It creates a new file if it doesn't exist |
Reading from and writing to files
Reading a file
Writing to a file
Appending to a file
File paths and directories
Python’s os
and pathlib
modules help in working with file paths and directories.
Using os
:
Using pathlib
:
File Object Methods: File Attributes
.name
: Returns the name of the file..mode
: Returns the mode in which the file was opened..closed
: Returns True if the file is closed, otherwise False.
Example:
Output:
File Object Methods: Reading Methods
.read(size)
: Reads the entire file or a specified number of bytes..readline()
: Reads a single line from the file..readlines()
: Reads all lines and returns a list.
Example:
Output:
File Object Methods: Writing Methods
.write(string)
: Writes a string to the file..writelines(iterable)
: Writes multiple lines from an iterable.
Example:
Error Handling
Errors may occur when working with files, such as trying to read a non-existent file.
Using exception handling (try-except) prevents crashes.
Pickle
The pickle
module allows serializing Python objects in a file, preserving their structure for later retrieval and deserialization.
Example of serializing:
Example of deserializing:
Output:
Always use binary mode (wb
/rb
) when working with pickle.
Only works within Python, cannot be directly deserialized by other languages.
Be cautious when deserializing untrusted data, as it can execute arbitrary code.
Shelve
The shelve
module provides a way to store and retrieve Python objects like a dictionary.
It uses pickle
internally but offers key-value access.
Example of storing data:
Example of retrieving data:
Output:
Works like a dictionary
but persists between executions.
Automatically handles file storage without needing explicit serialization.
Supports only string keys; values can be any serializable object.