1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
2. 分别把 string, list, tuple, dict写入到文件中
#!/usr/bin/env python
#coding:utf8
import random
import codecs
def getList():
l = []
for i in range(10):
num = random.randint(1,100)
l.append(num)
l.sort(reverse=False)
print("随机生成的列表由小到大排序:{0}".format(l))
return l
def wFile(l,mode):
with codecs.open("testList.txt",'{0}b'.format(mode)) as fd:
if mode == "a":
fd.write('
')
fd.write("{0}".format(l))
def rFile():
with codecs.open("testList.txt",'rb') as fd:
for line in fd.readlines():
newL = line.lstrip('[').rstrip(']').split(',')
newList = [int(i) for i in newL]
newList.sort(reverse=True)
print("反序后的列表是:{0}".format(newList))
wFile(newList,'a')
string1 = "123456789,hello world !"
print(type(string1))
list1 = ['a','b','c']
print(type(list1))
tuple1 = (1,2,"abc","efc")
print(type(tuple1))
dict1 = {"name":"cnblogs","age":"20"}
print(type(dict1))
if __name__=="__main__":
l = getList()
wFile(l,'w')
rFile()
print("分别把 string, list, tuple, dict写入到文件中")
wFile(string1,"a")
wFile(list1,"a")
wFile(tuple1,"a")
wFile(dict1,"a")
代码运行结果:
<type 'str'> <type 'list'> <type 'tuple'> <type 'dict'> 随机生成的列表由小到大排序:[30, 46, 53, 53, 55, 65, 68, 83, 84, 95] 反序后的列表是:[95, 84, 83, 68, 65, 55, 53, 53, 46, 30] 分别把 string, list, tuple, dict写入到文件中
最终testList.txt写入的内容
[30, 46, 53, 53, 55, 65, 68, 83, 84, 95] [95, 84, 83, 68, 65, 55, 53, 53, 46, 30] 123456789,hello world ! ['a', 'b', 'c'] (1, 2, 'abc', 'efc') {'age': '20', 'name': 'cnblogs'}