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())
程序运行结果: