Vinodh
Vinodh

Reputation: 1129

How to write to a file in a particular position using python?

i want to replace a dictionary value by mapping the key in the python file.how can it be done,someone help me,i am new in this field.sorry my english..

Upvotes: 2

Views: 419

Answers (1)

Jeffrey Kevin Pry
Jeffrey Kevin Pry

Reputation: 3296

I'm not quite sure I understand your question, but I'll try to help.

To save an object to file from Python you can use a process called Pickle.

What you would do is write your object to the file and then if you would like to change it, you can unpickle, change the value, and repickle.

import pickle

# Write object to file 
sampleDict = {'a': 1, 'b': 2, 'c': 3}
output = open('dictionary.pickle', 'wb')
pickle.dump(sampleDict, output)
output.close()

# Read object back in
pickledDictionary = open('dictionary.pickle', 'rb')
reimportSampleDict = pickle.load(pickledDictionary)
pickledDictionary.close()

# So far so good... No we add an item and repickle.
sampleDictNew['new_value'] = 4
pickledDictionary = open('dictionary.pickle', 'rb')
pickle.dump(reimportSampleDict, output)
pickledDictionary.close()

print sampleDict
print reimportSampleDict

Please note, that if you are trying to sort the keys on a standard dictionary in Python, it is a bad idea. Python doesn't guarantee that the keys will retain their position that they were added in.

If you need to be able to sort a dictionary by keys and reliably insert at certain positions in the dictionary, try using Python 3 with the new Ordered Dictionary collection. See here for more details about this: http://docs.python.org/dev/whatsnew/2.7.html#pep-0372.

If you use Python 2.* then check out: http://www.voidspace.org.uk/python/odict.html, as it offers similar functionality.

Either way, the same Pickle process can be used for the Dictionary object and the Ordered Dictionary object.

I hope this helps,

Jeffrey Kevin Pry

Upvotes: 1

Related Questions