将字符串,列表或词典保存为.txt文件

时间:2015-08-26 03:07:39

标签: python-3.x

我想要做的是能够在程序中修改字符串,列表或字典,并能够将修改后的字符串,列表或字典保存为下次运行程序时的起始数据。谁能告诉我它是如何完成的?

Ex:Strings

stringFile = open('stringName.txt', 'wt')

myString = 'Hello'

现在修改字符串,

myString.upper()
if 'l' in myString:
    myString = myString.replace('l','k')
    myString += ' World'


stringFile.write(str(myString))
stringFile.close()

Ex:列表

listFile = open('listName.txt', 'wt')

myList = [10,1,21,3,4,11,9,13,14]

现在修改列表,

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',
}

现在修改字典,

myDictionary[11] = 'Sodium'
myDictionary[12] = 'Magnesium'

keys = myDictionary.keys()
values = myDictionary.values()

dFile.write(str(keys))
dFile.write(str(values))
dFile.close()

现在,我已经修改了我的字符串,列表和字典...我想关闭程序并能够在下次启动修改后的数据。 我该怎么做???

如果您发现上述任何错误,请告诉我

谢谢

1 个答案:

答案 0 :(得分:0)

存储数据以便以后检索数据的最简单方法是序列化。序列化的常见格式是JSON

public class CustomAdapter extends ArrayAdapter<ItemMenu> {

    Context context;
    int resource;
    List<ItemMenu> objects;

    public CustomAdapter(Context context, int resource, List<ItemMenu> objects) {
        super(context, resource, objects);
        // TODO Auto-generated constructor stub
        this.context = context;
        this.resource = resource;
        this.objects = objects;

    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view=View.inflate(context, resource, null);
        ImageView img=view.findViewById();
        return super.getView(position, convertView, parent);
    }

}

反序列化

import json

with open(..., 'w') as fp:
  json.dump(val, fp)