Comprehensive Python Snippets: JSON Conversion, Date/Time Formatting, File I/O, QR & Barcode Generation, List & JSON Comparison, Class Reflection, and File Size Management
This article presents a collection of Python code examples covering JSON serialization, date‑time formatting, file reading, QR‑code and barcode creation, list and JSON comparison, class method reflection, and automatic file‑size‑based cleanup, providing practical guidance for everyday scripting tasks.
1. List to JSON and String to JSON – Use the built‑in json module to serialize a Python list or deserialize a JSON‑formatted string.
import json
my_list = ['apple', 'banana', 'cherry']
json_data = json.dumps(my_list)
print(json_data) # ["apple", "banana", "cherry"]
my_string = '{"name": "John", "age": 30, "city": "New York"}'
json_data = json.loads(my_string)
print(json_data) # {'name': 'John', 'age': 30, 'city': 'New York'}Note: json.loads() returns a Python dict ; use json.dumps() to obtain a JSON string.
2. Date/Time Formatting – Convert between strings, datetime objects, and timestamps using the datetime module.
from datetime import datetime
# String to datetime object
string_time = '2022-04-21 13:30:00'
time_obj = datetime.strptime(string_time, '%Y-%m-%d %H:%M:%S')
print(time_obj) # 2022-04-21 13:30:00
# Datetime object to string
time_obj = datetime.now()
string_time = time_obj.strftime('%Y-%m-%d %H:%M:%S')
print(string_time) # e.g., 2023-04-21 16:52:22
# Timestamp to datetime and back
timestamp = 1650649800
time_obj = datetime.fromtimestamp(timestamp)
print(time_obj) # 2022-12-21 12:30:00
timestamp = int(time_obj.timestamp())
print(timestamp) # 16506498003. Reading Files – Open files with open() using relative or absolute paths; with ensures automatic closure.
# Read a file in the current directory
with open('example.txt', 'r') as f:
content = f.read()
print(content)
# Read a file using an absolute path
with open('/home/user/Documents/example.txt', 'r') as f:
content = f.read()
print(content)For cross‑platform paths, prefer the os.path utilities.
4. QR‑Code Image Generation – The qrcode library creates QR codes with configurable version, error correction, box size, and border.
import qrcode
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10, border=4)
data = 'https://www.example.com/'
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color='black', back_color='white')
img.save('qrcode.png')Install the library with pip install qrcode .
5. Barcode Image Generation – Use the python-barcode package to generate EAN13 (or other) barcodes.
import barcode
from barcode.writer import ImageWriter
data = '123456789'
ean = barcode.get('ean13', data, writer=ImageWriter())
filename = ean.save('barcode')Install with pip install python-barcode .
6. Bulk ID Card Generation – The id-validator library can create valid Chinese ID numbers.
from id_validator import validator
for i in range(10):
id_card = validator.create_id_card()
print(id_card)Install with pip install id-validator . Use responsibly and comply with local regulations.
7. List Data Comparison – Compare two lists using set operations or list comprehensions.
# Using sets
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
set1, set2 = set(list1), set(list2)
intersection = list(set1.intersection(set2))
union = list(set1.union(set2))
difference = list(set1.difference(set2))
print(intersection, union, difference)
# Using list comprehensions
intersection = [x for x in list1 if x in list2]
union = list(set(list1 + list2))
difference = [x for x in list1 if x not in list2]
print(intersection, union, difference)8. JSON Data Comparison – Parse JSON strings to Python objects and compare keys/values.
import json
json_str1 = '{"name": "Tom", "age": 18, "gender": "male"}'
json_str2 = '{"name": "Jerry", "age": 20, "gender": "male"}'
data1 = json.loads(json_str1)
data2 = json.loads(json_str2)
for key in data1:
if key in data2:
if data1[key] != data2[key]:
print(key, "different:", data1[key], data2[key])
else:
print(key, "missing in second JSON")
for key in data2:
if key not in data1:
print(key, "missing in first JSON")Ensure the JSON strings are well‑formed before loading.
9. Bulk Retrieval of Class Methods – Use reflection to list callable attributes of a class.
class MyClass:
def __init__(self, name):
self.name = name
def my_method1(self):
pass
def my_method2(self):
pass
@classmethod
def my_classmethod(cls):
pass
@staticmethod
def my_staticmethod():
pass
methods = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
for method in methods:
print(method)For detailed signatures, consider the inspect module.
10. File Size‑Based Automatic Cleanup – Continuously monitor a file and delete it when it exceeds a size limit, pausing between checks.
import os, time
def clear_file(file_path, limit_size=1024*1024, clear_interval=3600):
"""Delete the file when its size exceeds *limit_size*; repeat every *clear_interval* seconds."""
while True:
file_size = os.path.getsize(file_path)
if file_size > limit_size:
os.remove(file_path)
print("File cleared:", file_path)
else:
print("File size within limit:", file_path)
time.sleep(clear_interval)
# Example usage
clear_file("test.txt", limit_size=1024*1024, clear_interval=3600)Handle potential exceptions (e.g., file in use) when integrating into production systems.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.