复习作业
复习作业
1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
2. 分别把 string, list, tuple, dict写入到文件中
1,利用ast.literal_eval,将字符串型的list,tuple,dict转变成原有的类型
import codecs import ast L = [2,4,6,8,9,1,3,5,7,23,567,356] with codecs.open('1.txt', 'wb') as f: f.write(str(sorted(L))) with codecs.open('1.txt', 'rb') as f1: a = f1.read() L2 = ast.literal_eval(a) L2.reverse() with codecs.open('1.txt', 'ab') as f2: f2.write('\n') f2.write(str(L2)) with codecs.open('1.txt', 'rb') as f2: L3 = f2.read() print L3
结果
[1, 2, 3, 4, 5, 6, 7, 8, 9, 23, 356, 567]
[567, 356, 23, 9, 8, 7, 6, 5, 4, 3, 2, 1]
2
#!/usr/bin/env python # coding=utf-8 import codecs import ast #string写入文件 with codecs.open('2.txt','wb') as f: f.write('python') f.write('\n') ##list写入 L = [1,'a','b',4,'python'] with codecs.open('2.txt','ab') as f: f.write(str(L)) f.write('\n') ##tuple写入 T = (2,'c','py',5) with codecs.open('2.txt','ab') as f: f.write(str(T)) f.write('\n') ##dict写入 D = {'name':'liang','age':100} with codecs.open('2.txt','ab') as f: f.write(str(D)) f.write('\n') ##内容打印 with codecs.open('2.txt','rb') as f: f.seek(0) S1 = f.readline() L1 = ast.literal_eval(f.readline()) T1 = ast.literal_eval(f.readline()) D1 = ast.literal_eval(f.readline()) for i in (S1,L1,T1,D1): print i print type(i)
结果
python <type 'str'> [1, 'a', 'b', 4, 'python'] <type 'list'> (2, 'c', 'py', 5) <type 'tuple'> {'age': 100, 'name': 'liang'} <type 'dict'>
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">
posted on 2017-10-31 00:35 song-liang 阅读(166) 评论(0) 收藏 举报