简体   繁体   中英

Python Tuple save to file

def save(val):
    w = open(val, "w")
    for key in self.bok.iterkeys():
        w.write(self.bok[key])
        w.write(";")
        w.write(key[0])
        w.write(";")
        w.write("\n")
    w.close()

If my dict looks like

bok = {(1,2,3,4,5) : 22}

i would like to write all the tuples in my key to the value in a file, so it looks like

22;1
22;2
22;3
etc... 

Currently I only get the first value in my tuple to write to a file, 22;1 . I know I get it by key[0] but I cant really change it.

Is there any way to make this work? Any help is appreciated.

I think you need to nest a second for loop here:

for key in self.bok.iterkeys():
    for subkey in key:
        w.write(self.bok[key])
        w.write(";")
        w.write(subkey)
        w.write(";")
        w.write("\n")
w.close()

Also, consider using some string formatting:

for key in self.bok.iterkeys():
    for subkey in key:
        w.write("{};{};\n".format(self.bok[key], subkey))
w.close()

I would highly recommend serializing the dictionary.The pickle module provides support for this! An example program for you:

    import pickle ##Import the pickle module
    bok = {(1,2,3,4,5) : 22} #Define the dictionary
    w = open(val, "wb")#Open the file
    pickle.dump(bok, w)#Dump the dictionary bok, the first parameter into the file object w.
    w.close()

You must open the file in "wb" mode because, pickles are binary data. After running this code the file val will contain binary data.

To bring the dictionary back:

    import pickle#import the pickle module
    w=open(val, 'rb')#Open the file
    bok=pickle.load(w)#Assign the recreated object to bok

Basically pickle.dump() translates objects into binary data that can be written to files. pickle.load() reads the given file and returns the reconstructed object.

This works for many python objects besides dictionaries, like lists and booleans.

Python docs for pickle : http://docs.python.org/3.4/library/pickle.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM