您可以使用csv 模块来完成大部分工作来解析文件并在您进行更改后将其写回——所以它应该相对容易使用。我从其中一个answers 中得到了这个想法,并提出了一个名为Using ConfigParser to read a file without section name 的类似问题。
但是我已经对其进行了许多更改,包括对其进行编码以在 Python 2 和 3 中工作,取消对它使用的键/值分隔符进行硬编码,使其几乎可以是任何东西(但默认情况下是冒号),以及一些优化。
from __future__ import print_function # For main() test function.
import csv
import sys
PY3 = sys.version_info.major > 2
def read_properties(filename, delimiter=':'):
""" Reads a given properties file with each line in the format:
key<delimiter>value. The default delimiter is ':'.
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
The default delimiter is ':'.
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) # Create csv from data dictionary.
newdata = read_properties(filename) # Read it back into a new dictionary.
print('Properties read: ')
print(newdata)
print()
# Show the actual contents of file.
with open(filename, 'rb') as propfile:
contents = propfile.read().decode()
print('File contains: (%d bytes)' % len(contents))
print('contents:', repr(contents))
print()
# Tests whether data is being preserved.
print(['Failure!', 'Success!'][data == newdata])
if __name__ == '__main__':
main()