Created
September 1, 2014 10:43
-
-
Save jorge-lavin/272b554384c817b49c4f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function # only for module main() test function | |
import csv | |
import sys | |
PY3 = sys.version_info[0] > 2 | |
def read_properties(filename, delimiter=':'): | |
''' Reads a given properties file with each line of the format key=value. | |
Returns a dictionary containing the pairs. | |
filename -- the name of the file to be read | |
''' | |
open_kwargs = dict(mode='r', newline='') if PY3 else dict(mode='rb') | |
with open(filename, **open_kwargs) as csvfile: | |
reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\', | |
quoting=csv.QUOTE_NONE) | |
return {row[0]: row[1] for row in reader} | |
def write_properties(filename, dictionary, delimiter=':'): | |
''' Writes the provided dictionary in key sorted order to a properties | |
file with each line of the format key<delimiter>value | |
filename -- the name of the file to be written | |
dictionary -- a dictionary containing the key/value pairs. | |
''' | |
open_kwargs = dict(mode='w', newline='') if PY3 else dict(mode='wb') | |
with open(filename, **open_kwargs) as csvfile: | |
writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\', | |
quoting=csv.QUOTE_NONE) | |
writer.writerows(sorted(dictionary.items())) | |
def main(): | |
data = { | |
'Answer': '6*7=42', | |
'Knights': 'Ni!', | |
'Spam': 'Eggs', | |
} | |
filename='test.properties' | |
write_properties(filename, data) | |
newdata = read_properties(filename) | |
print('Read in: ') | |
print(newdata) | |
print() | |
with open(filename, 'rb') as propfile: | |
contents = propfile.read() | |
print('File contents: (%d bytes)' % len(contents)) | |
print(contents) | |
print(['Failure!', 'Success!'][data == newdata]) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment