python文件操作一

复习上周的内容
说明:根据投票,多数同学建议复习一下。所以给两天时间,同学们抓紧时间好好消化。
实现如下:
1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
2. 分别把 string, list, tuple, dict写入到文件中

 1 #! /usr/bin/env python
 2 #  _*_ coding:utf-8 _*_
 3 #  @Time    :2017/10/30  17:45
 4 #  @Author   :Kelake
 5 #  @FileName :复习一.py
 6 
 7 # 三周一次课(10月30日)三周二次课(10月31日)
 8 # 复习上周的内容
 9 # 说明:根据投票,多数同学建议复习一下。所以给两天时间,同学们抓紧时间好好消化。
10 # 实现如下:
11 # 1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
12 # 2. 分别把 string, list, tuple, dict写入到文件中
13 
14 L1 = [1,2,5,7,23,47,77,97,6,4,44,32,27]
15 S1 = "ace12367bcd"
16 T1 = (123,456,"abc","dev","456")
17 D1 = {"name":"King" , "sex":"man" , "age":"30"}
18 print "Display list L1:" , L1
19 print "Display str S1:" , S1
20 print "Display tuple T1:" , T1
21 print "Display dict D1:" , D1
22 
23 #小到大排序
24 L1.sort()
25 print "列表L1从小到大的排序是:",L1
26 L1.sort()
27 L2 = str(L1)
28 print type(L2)
29 print L2
30 print  "将L1列表从小排到大写入文件test.txt中"
31 import  codecs
32 L3 = codecs.open("test.txt" , "w")
33 L3.write(L2 + "
")
34 L3.close()
35 print "读取test.txt里面的内容,并将里面的内容转换成列表,并从大到小排序。"
36 L4 = codecs.open("test.txt" , "r")
37 L5 = L4.read()
38 L4.close()
39 print L5
40 print type(L5)
41 L6 = eval(L5)
42 print L6
43 print type(L6)
44 L6.reverse()
45 print L6
46 L7 = str(L6)
47 print "读取test.txt里面的内容,并将里面的内容转换成列表,并从大到小排序,然后追加到test.txt的文件中。"
48 L8 = codecs.open("test.txt" , "a+")
49 L8.write(L7 + "
")
50 L8.close()
51 print "将字符串追加到test.txt的文件中。"
52 
53 S2 = codecs.open("test.txt" , "a+")
54 S2.write(S1 + "
")
55 S2.close()
56 
57 print "将元组追加到test.txt的文件中。"
58 T2 = str(T1)
59 T3 = codecs.open("test.txt" , "a+")
60 T3.write(T2 + "
")
61 T3.close()
62 
63 print "将字典追加到test.txt的文件中。"
64 D2 = str(D1)
65 D3 = codecs.open("test.txt" , "a+")
66 D3.write(D2 + "
")
67 D3.close()
68 
69 L9 = list(D1)
70 print type(L9)
71 print L9
72 print dict.values(D1)
73 print dict.keys(D1)
练习题

运行截图:

生成的test.txt文件截图:

原文地址:https://www.cnblogs.com/kelake/p/7762868.html