首页 > 编程语言 > 详细

python 10月30日复习

时间:2017-10-30 22:39:42      阅读:294      评论:0      收藏:0      [点我收藏+]

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

import codecs

list1 = [2,23,8,54,86,12]
list1.sort()

with codecs.open(‘1.txt‘,‘wb‘) as f:
    f.write(str(list1))


with codecs.open(‘1.txt‘,‘rb‘) as f:
    print (f.read())


list1.reverse()
with codecs.open(‘1.txt‘,‘ab‘) as f:
    f.write(‘\n‘)
    f.write(str(list1))


with codecs.open(‘1.txt‘,‘rb‘) as f:
    print (f.read())

  程序运行结果:

技术分享

 

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

import codecs

string = ‘abc‘
li = [‘aa‘,‘bb‘,‘cc‘,‘dd‘]
tu = (‘ee‘,‘ff‘,‘gg‘,‘hh‘)
di = {"name":"huangdongju","age":20 }

with codecs.open(‘2.txt‘,‘wb‘) as file:
    file.write(string+‘\n‘)
    file.write(str(li)+‘\n‘)
    file.write(str(tu)+‘\n‘)
    file.write(str(di))

with codecs.open(‘2.txt‘,‘rb‘) as file:
    print (file.read())

程序运行结果:

技术分享

 

python 10月30日复习

原文:http://www.cnblogs.com/huangdongju/p/7757955.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!