码迷,mamicode.com
首页 > 编程语言 > 详细

python 10月30日复习

时间:2017-10-30 22:43:41      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:内容   log   logs   with   blog   pre   python   写入   一个   

 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日复习

标签:内容   log   logs   with   blog   pre   python   写入   一个   

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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!