Basic File IO
# Note: As this requires read-write access to your hard drive,
# this will not run in the browser in Brython.
def readFile(path):
with open(path, "rt") as f:
return f.read()
def writeFile(path, contents):
with open(path, "wt") as f:
f.write(contents)
contentsToWrite = "This is a test!\nIt is only a test!"
writeFile("foo.txt", contentsToWrite)
contentsRead = readFile("foo.txt")
assert(contentsRead == contentsToWrite)
print("Open the file foo.txt and verify its contents.")
Here is another more-complete example that saves and loads data from a file:
# Here is an example that saves and loads data from a file.
# It works well with builtin data types. It's a bit more complicated
# to do this with custom classes. For those, you have to be sure
# that your __repr__ method returns a string such that
# (eval(v.__repr__()) == v) is True.
import ast
def readFile(path):
with open(path, "rt") as f:
return f.read()
def writeFile(path, contents):
with open(path, "wt") as f:
f.write(contents)
# Place all your data in a dictionary, like so:
myData = {
'names': ['fred', 'wilma', 'betty'],
'highScores': [32, 41, 18, 17, 64],
'stateCapitals': { 'pa':'harrisburg', 'oh':'columbus' },
'setOfPrimes': { 2, 3, 5, 7, 11 },
}
# Then, you can save your data to a file like so:
writeFile('myData.txt', repr(myData))
# Later on, you can restore your data from the file like so:
myData1 = ast.literal_eval(readFile('myData.txt'))
# Finally, let's confirm that these two dictionaries are equal:
print(myData1 == myData) # True!