What I want to do is be able to modify a string, list, or dictionary during the program and be able to save the modified string, list, or dictionary as the starting data for the next time I run the program. Can anyone show me how its done?
Ex: Strings
stringFile = open('stringName.txt', 'wt')
myString = 'Hello'
Now modify the string,
myString.upper()
if 'l' in myString:
myString = myString.replace('l','k')
myString += ' World'
stringFile.write(str(myString))
stringFile.close()
Ex: Lists
listFile = open('listName.txt', 'wt')
myList = [10,1,21,3,4,11,9,13,14]
Now modify the list,
myList.append(24)
myList = myList.sort()
listFile.write(str(myList))
listFile.close()
Ex: Dictionary
dFile = open('dictionaryName.txt', 'wt')
myDictionary = {
1: 'Hydrogen',
2: 'Helium',
3: 'Lithium',
4: 'Beryllium',
5: 'Boron',
6: 'Carbon',
7: 'Nitrogen',
8: 'Oxygen',
9: 'Fluorine',
10: 'Neon',
}
Now modify the dictionary,
myDictionary[11] = 'Sodium'
myDictionary[12] = 'Magnesium'
keys = myDictionary.keys()
values = myDictionary.values()
dFile.write(str(keys))
dFile.write(str(values))
dFile.close()
Now, that I have modified my string, list, and dictionary...I want to close the program and be able to start with that modified data for next time. HOW DO I DO THAT???
If you notice any errors above, please tell me
Thank You
The easiest way to store data so that it can be retrieved at a later time is to serialize it. A common format for serialization is JSON .
import json
with open(..., 'w') as fp:
json.dump(val, fp)
And to deserialize it:
import json
with open(..., 'r') as fp:
val = json.load(fp)
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.