python 基础 3.2 文件 for 练习

#/usr/bin/python
#coding=utf-8
#@Time   :2017/11/1 22:19
#@Auther :liuzhenchuan
#@File   :1030-1031练习题.py
 
###1 把一个数字的list从小到大排序,然后写到文件中,然后从文件中读取文件内容然后反序,在追加到文件的
   #下一行中
###2 分别把string list tuple dict 写到文件中
import codecs
 
l1 = [51,34,67,8,10,11,9]
l1.sort()
l2 = str(l1)
print l2
 
with open('a.txt','w+') as fd:
    for i in l2:
        fd.write(str(i))
    fd.write(' ')
    fd.close()
  #打印出文件内容
with open('a.txt') as fd:
    print fd.read(),
 
#反序追加到文件的下一行中
l1.reverse()
l3 = str(l1)
with open('a.txt','a') as fd:
    for j in l3:
        fd.write(str(j))
        # fd.write(' ')
    fd.close()
#打印出文件内容
with open('a.txt') as fd:
    print fd.read()
>>> [8, 9, 10, 11, 34, 51, 67]
  [67, 51, 34, 11, 10, 9, 8]
 
####2 分别把string list tuple dict 写到文件中去
#把字符串写到文件中去
str1 = 'abcde'
with open('b.txt','w+') as f:
    f.write(' '.join(str1))
with open('b.txt') as f:
    print f.read()
>>> a b c d e
 
#把列表写到字符串中去,并用空格隔开每个字符
list1 = [1,2,3,4,5,6]
with open('c.txt','w+') as f1:
    # for i in list1:
    #     f1.write(str(i))
    # f1.close()
    f1.write(''.join([str(i)+' ' for i in list1 ]))
with open('c.txt') as f1:
    print f1.read()
>>> 1 2 3 4 5 6
 
#把元组写到文件中去
tuple1 = ('1','2','a','b')
with codecs.open('d.txt','w+') as f2:
f2.write(str(tuple1) + ' ')
f2.close()
with codecs.open('d.txt') as f2:
    print f2.read()
>>> ('1', '2', 'a', 'b')
 
#把字典写到文件中去
dict1 = {'a':'1','b':2,'c':3}
with open('e.txt','w+') as f3:
    f3.write(str(dict1))
with open('e.txt') as f3:
    print f3.read()
>>> {'a': '1', 'c': 3, 'b': 2}
 
原文地址:https://www.cnblogs.com/lzcys8868/p/7769247.html