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

Python 第三周作业

时间:2017-10-30 14:40:30      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:code   .so   eve   blog   reverse   pre   str   log   ict   

1、把一个数字的 list 从小到大排序,然后写入文件,然后从文件中读取出来文件内容: 

In [13]: l = [2, 32, 43, 453, 54, 6, 576, 5, 7, 6, 8, 78, 7, 89]

In [14]: l.sort()

In [17]: with open(1.txt, w) as fd:
   ....:     fd.write(str(l))
   ....:     

In [18]: with open(1.txt) as fd:
   ....:     print fd.read()
   ....:     
[2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]

2、然后反序,再追加到文件的下一行中:

In [19]: l.reverse()

In [20]: with open(1.txt, a) as fd:
   ....:     fd.write(str(l))
   ....:     

In [21]: with open(1.txt) as fd:
   ....:     print fd.read()
   ....:     
[2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]
[576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]

3、分别把 string, list, tuple, dict 写入到文件中:

In [21]: string = abc
In [22]: list = [a, b, c]
In [23]: tuple = (a, b, c)
In [24]: dict = {1:a, 2:b, 3:c}

In [25]: with open(1.txt, w) as fd:
   ....:     fd.write(string+\n)
   ....:     fd.write(str(list)+\n)
   ....:     fd.write(str(tuple)+\n)
   ....:     fd.write(str(dict))
   ....:     

In [26]: with open(1.txt) as fd:
   ....:     print fd.read()
   ....:     
abc
[a, b, c]
(a, b, c)
{1: a, 2: b, 3: c}

 

 

 

 

 

     

 

Python 第三周作业

标签:code   .so   eve   blog   reverse   pre   str   log   ict   

原文地址:http://www.cnblogs.com/pzk7788/p/7753604.html

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