-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileIO.py
52 lines (40 loc) · 1.4 KB
/
fileIO.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""
fileIO.py
~~~~~~~~~~~~~~~
General file input-output functions.
"""
# Standard libraries
import pickle
import os
from time import localtime, strftime
# Creates new file and saves contents using pickle to serialize
def writeTo(filename, contents):
with open(filename, "wt") as f:
# write contents to file object f
pickle.dump(contents, f, pickle.HIGHEST_PROTOCOL)
# Deserializes pickled object and returns the original data structure
def read(filename):
with open(filename, "rt") as f:
contents = pickle.load(f)
return contents
# Specialized for the data directory, where filenames are creation times
def openRecent(directory):
filename = bottomFile(directory)
return read(filename)
# Returns last filename in a sorted list of all filenames in a directory
def bottomFile(directory):
return directory + os.sep + sorted(os.listdir(directory))[-1]
# Takes a list of dictionaries, returns list of (key, value) tuples
def processDictList(a):
tuples = []
for d in a:
for key in d.keys():
tuples.append((key, d[key]))
return tuples
# Takes a file of a list of dictionaries, returns list of (key, value) tuples
def processDictListFile(filename):
lst = read(filename)
return processDictList(lst)
# returns string in MMDDYY_HHMMSS format (month/day/year_hour/min/sec)
def timeStr():
return strftime("%m%d%y_%H%M%S", localtime())