Chinaunix首页 | 论坛 | 博客
  • 博客访问: 230706
  • 博文数量: 57
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2015-10-01 18:05
文章分类

全部博文(57)

文章存档

2017年(57)

我的朋友

分类: Python/Ruby

2017-10-31 01:47:18

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

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.Xie
  4. # @Time :2017/10/30 21:48
  5. # @File :mysort.py

  6. # 把一个数字的list从小到大排序,然后写入文件,
  7. # 然后再从文件中读取出来文件内容,反序排列,再追加到文件的下一行中
  8. import codecs

  9. import re

  10. lists = [2, 32, 43, 453, 54, 6, 576, 5, 7, 6, 8, 78, 7, 89]


  11. def fanxu(lists):
  12.     count = len(lists)
  13.     for i in range(0, count):
  14.         for j in range(i + 1, count):
  15.             if lists[i] < lists[j]:
  16.                 lists[i], lists[j] = lists[j], lists[i]
  17.     fo = open("sort.txt", "a")
  18.     fo.write('\n')
  19.     fo.write(str(lists))
  20.     fo.close()


  21. def asort(alist):
  22.     blist = sorted(lists)
  23.     writefile(str(blist))


  24. def readfile():
  25.     fo = codecs.open("sort.txt", "r")
  26.     for line in fo.readlines():
  27.         line = line.strip()
  28.     find_lst = re.findall('\[(.*?)\]', line)
  29.     result = find_lst[0].strip(',').split(',')
  30.     blist = map(eval, result)
  31.     # paixu(blist)
  32.     fo.close()
  33.     fanxu(blist)


  34. def writefile(afile):
  35.     fo = open("sort.txt", "w")
  36.     fo.write(afile)
  37.     fo.close()


  38. if __name__ == '__main__':
  39.     asort(lists)
  40.     readfile()
执行结果:

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


点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author :Alvin.Xie
  4. # @Time :2017/10/30 21:45
  5. # @File :writefile.py

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

  7. astr = "I love python"
  8. alist = [2, 6, 3, 9, 10, 12, 7]
  9. atuple = ('a', 'p', 'y', 't', 'h', 'o', 'n')
  10. adict = {'name': 'tom', 'address': 'shanghai'}

  11. # print astr
  12. # print alist
  13. # print atuple
  14. # print adict

  15. blist = str(alist)
  16. btuple = str(tuple(atuple))
  17. bdict = str(adict)


  18. def writefile(afile):
  19.     fo = open("test.txt", "a")
  20.     fo.write(afile)
  21.     fo.write('\n')
  22.     fo.close()


  23. if __name__ == '__main__':
  24.     writefile(astr)
  25.     writefile(blist)
  26.     writefile(btuple)
  27.     writefile(bdict)
执行结果:


阅读(1373) | 评论(0) | 转发(0) |
0

上一篇:文件的操作

下一篇:python 函数

给主人留下些什么吧!~~