python学习-Day11-12-复习

来源:互联网 发布:毕向东java笔记 编辑:程序博客网 时间:2024/06/03 21:40

 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行


list = [4,22,445,678,43,678,43,45,92 ]
list1 = sorted(list)

f = open('2.txt','a')
f.writelines(str(list1))
f.writelines('\n')
f.close()

fd = open('2.txt')
a2 = fd.readlines()
print (a2)
fd.close()


['[2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]\n', '[576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]\n']


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

#!/usr/bin/env python
# -*- coding:utf-8 -*

string = 'this si a string'
list1 = ['hello','word','you']
tuple1 = ('hello','word','you')
dict1 = {'a':1,'b':2,'c':3}
 
with open('3.txt','w') as fd:
    fd.write(string + '\n')
    fd.write(str(list1) + '\n')
    fd.write(str(tuple1) + '\n')
    fd.write(str(dict1) + '\n')
 
with open('3.txt','r') as fd:
    = fd.read()
    print(a)
 
输出结果
this si a string
['hello''word''you']
('hello''word''you')
{'a'1'b'2'c'3}