[英]Saving a String, List, or Dictionary as a .txt file
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 .
序列化的常见格式是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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.