Python 第三周作业
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 第三周作业相关的知识,希望对你有一定的参考价值。
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 第三周作业的主要内容,如果未能解决你的问题,请参考以下文章