1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中

>>> import json
>>> import codecs
>>>
>>> a = [12,34,121,324,14,2,345,13,2,5,1,35,6,23,235,123,21232234]
>>> a.sort() # 原地排序
>>> a
[1, 2, 2, 5, 6, 12, 13, 14, 23, 34, 35, 121, 123, 235, 324, 345, 21232234]
>>> with codecs.open('text.txt','w') as f:
... f.write(json.dumps(a)) # 写入文件前的序列化
...
>>> with codecs.open('text.txt','r') as f:
... b = json.loads(f.read()) # 读取并反序列化
...
>>> b
[1, 2, 2, 5, 6, 12, 13, 14, 23, 34, 35, 121, 123, 235, 324, 345, 21232234]
>>> b.reverse() # 倒序排列
>>> b
[21232234, 345, 324, 235, 123, 121, 35, 34, 23, 14, 13, 12, 6, 5, 2, 2, 1]
>>> with codecs.open('text.txt','a+') as f:
... f.write(json.dumps(b)) # 追加模式写入文件
...

2. 分别把 string, list, tuple, dict写入到文件中

  这里如果对tuple进行序列化的时候会出现一个问题,虽说json支持对tuple类型的数据进行序列化,但是,序列化完毕后变成了list,并且反序列化回来后依旧为list,元素类型都变为了unicode,所以这里如果为了还原tuple,那么最好使用pickle,当然如果和其他api进行交互,那么建议都使用dict这种形式

>>> import codecs
>>> import json
>>> a = 'hello world'
>>> b = ['hello','world']
>>> c = ('hello','world')
>>> d = {'hello':'world'}
>>> with codecs.open('test.txt','w') as f:
... f.write(json.dumps(a))
... f.write(json.dumps(b))
... f.write(pickle.dumps(c))
... f.write(json.dumps(d))
...

  

最新文章

  1. Java 8函数编程轻松入门(五)并行化(parallel)
  2. sqlserver字段类型
  3. 【RQNOJ356】myt的格斗
  4. Jquery_jquery中attr和prop的区别
  5. 删除DSO Change Log表数据
  6. MySQL数据库的基本数据类型
  7. java 笔记(2) —— 内部类的作用
  8. java面向对象编程— —第七章 继承
  9. android错误 Android NAND: nand_dev_load_disk_state,
  10. MFC多线程内存泄漏问题&解决方法
  11. c语言字符串翻转系列
  12. redis使用场景和java测试案例
  13. python—迭代器、生成器
  14. Android WebView的HTML中的select标签不起作用
  15. JavaScript学习(七)
  16. Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'zoneId' in 'class java.lang.String'
  17. HD-SDI制式学习
  18. PHP:第一章——PHP中字符运算符、比较运算符、错误控制运算符
  19. Genymotion——VirtualBox cannot start virtual device
  20. JDK源码学习之 集合实现类

热门文章

  1. iOS中的数据库应用
  2. spring location设置本地路径
  3. 「暑期训练」「Brute Force」 Far Relative’s Problem (CFR343D2B)
  4. 「题目代码」P1007~P1012(Java)
  5. JQuery UI 日历加时间
  6. LeetCode - 35. Search Insert Position(48ms)
  7. svm+voting
  8. linux备忘录-账号管理与ACL权限设定
  9. HDU 4436 str2int(后缀自动机)(2012 Asia Tianjin Regional Contest)
  10. HDU 4745 Two Rabbits(最长回文子序列)(2013 ACM/ICPC Asia Regional Hangzhou Online)