Skip to content Skip to sidebar Skip to footer

Python - Writing A Variable To A Text File

So this is my very first attempt at Python and programming the Raspberry Pi. My small project is to light an LED when I get a mention on Twitter. All very simple and the code shown

Solution 1:

What you're looking for is called "serialization" and Python provides many options for that. Perhaps the simplest and the most portable one is the json module

import json

# read:

with open('ids.json', 'r') as fp:
    printed_ids = json.load(fp) 
    # @TODO: handle errors if the file doesn't exist or is empty

# write:

with open('ids.json', 'w') as fp:
    json.dump(printed_ids, fp)

Post a Comment for "Python - Writing A Variable To A Text File"