Fundamentals 14 min read

Python Code Snippets for Data Conversion, Date/Time Handling, File I/O, QR/Barcode Generation, List & JSON Comparison, and File Management

This article provides a collection of Python examples that demonstrate how to convert lists and strings to JSON, format dates and timestamps, read files, generate QR codes and barcodes, compare lists and JSON data, retrieve class methods via reflection, and automatically delete large files based on size and time.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Code Snippets for Data Conversion, Date/Time Handling, File I/O, QR/Barcode Generation, List & JSON Comparison, and File Management

1. List and String to JSON – Use the built‑in json module. 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 that json.loads() returns a Python dict , while json.dumps() produces a JSON string.

2. Date‑Time Formatting – Convert between strings, datetime objects, and timestamps using datetime.strptime() , datetime.strftime() , and datetime.fromtimestamp() / datetime.timestamp() . Example: from datetime import datetime string_time = '2022-04-21 13:30:00' time_obj = datetime.strptime(string_time, '%Y-%m-%d %H:%M:%S') print(time_obj) now = datetime.now() string_time = now.strftime('%Y-%m-%d %H:%M:%S') print(string_time) timestamp = 1650649800 time_obj = datetime.fromtimestamp(timestamp) print(time_obj)

3. Reading Files – Use open() with a context manager. Relative path example: with open('example.txt', 'r') as f: content = f.read() print(content) Absolute path example uses the full file system path; for cross‑platform code, prefer os.path utilities.

4. QR Code Generation – Install qrcode ( pip install qrcode ) and create an image: 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')

5. Barcode Generation – Install python-barcode ( pip install python-barcode ) and generate an EAN13 barcode: import barcode from barcode.writer import ImageWriter data = '123456789' ean = barcode.get('ean13', data, writer=ImageWriter()) filename = ean.save('barcode')

6. Bulk ID Card Generation – Use the id-validator library ( pip install id-validator ) to create valid Chinese ID numbers: from id_validator import validator for i in range(10): id_card = validator.create_id_card() print(id_card)

7. List Comparison – Compare two lists using set operations or list comprehensions. Set example: list1 = [1,2,3,4,5] list2 = [3,4,5,6,7] intersection = list(set(list1).intersection(list2)) union = list(set(list1).union(list2)) difference = list(set(list1).difference(list2)) print(intersection, union, difference) Comprehension example: 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]

8. JSON Data Comparison – Load two JSON strings with json.loads() and compare keys/values: import json json_str1 = '{"name": "Tom", "age": 18, "gender": "male"}' json_str2 = '{"name": "Jerry", "age": 20, "gender": "male"}' obj1 = json.loads(json_str1) obj2 = json.loads(json_str2) for key in obj1: if key in obj2: if obj1[key] != obj2[key]: print(key, "different:", obj1[key], obj2[key]) else: print(key, "missing in second JSON") for key in obj2: if key not in obj1: print(key, "missing in first JSON")

9. Retrieving All 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 @classmethod def my_classmethod(cls): pass @staticmethod def my_staticmethod(): pass methods = [m for m in dir(MyClass) if callable(getattr(MyClass, m))] for method in methods: print(method) For detailed signatures, the inspect module can be used.

10. Automatic File Deletion When Size Exceeds 1 MB – Combine os and time to monitor a file and delete it at a fixed interval: import os, time def clear_file(file_path, limit_size=1024*1024, clear_interval=3600): while True: size = os.path.getsize(file_path) if size > limit_size: os.remove(file_path) print('File cleared:', file_path) else: print('File size OK:', file_path) time.sleep(clear_interval) clear_file('test.txt') Use with caution as deletion is irreversible.

PythonreflectionDateTimeFile I/OQR codeData ConversionBarcode
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.