Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generate and parse Mac OS X .plist files using Python (plistlib)
Files with .plist extension are used by macOS applications to store application properties. The plistlib module provides an interface to read and write these property list files in Python.
The plist file format serializes basic object types like dictionaries, lists, numbers, and strings. Usually, the top-level object is a dictionary. Values can be strings, integers, floats, booleans, tuples, lists, and dictionaries (but only with string keys).
Main Functions
| Function | Description |
|---|---|
load() |
Read a plist file from a readable binary file object |
dump() |
Write value to a plist file via writable binary file object |
loads() |
Load a plist from a bytes object |
dumps() |
Return value as a plist-formatted bytes object |
Creating a Plist File
The following example stores a dictionary in a plist file ?
import plistlib
properties = {
"name": "Ramesh",
"College": "ABC College",
"Class": "FY",
"marks": {"phy": 60, "che": 60, "maths": 60}
}
with open('student.plist', 'wb') as file:
plistlib.dump(properties, file)
print("Plist file created successfully!")
Plist file created successfully!
Reading a Plist File
To read the plist file back, use the load() function ?
import plistlib
with open('student.plist', 'rb') as file:
data = plistlib.load(file)
print(data)
print(f"Student name: {data['name']}")
print(f"Physics marks: {data['marks']['phy']}")
{'name': 'Ramesh', 'College': 'ABC College', 'Class': 'FY', 'marks': {'phy': 60, 'che': 60, 'maths': 60}}
Student name: Ramesh
Physics marks: 60
Working with Bytes Objects
You can also work directly with bytes objects using dumps() and loads() ?
import plistlib
data = {"app": "TextEdit", "version": "1.0"}
# Convert to bytes
plist_bytes = plistlib.dumps(data)
print(f"Serialized length: {len(plist_bytes)} bytes")
# Parse from bytes
parsed_data = plistlib.loads(plist_bytes)
print(f"Parsed data: {parsed_data}")
Serialized length: 202 bytes
Parsed data: {'app': 'TextEdit', 'version': '1.0'}
Conclusion
The plistlib module makes it easy to work with macOS property list files in Python. Use dump()/load() for file operations and dumps()/loads() for working with bytes objects.
