生活随笔
收集整理的這篇文章主要介紹了
(三)3-1 练习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 把一個數字的list從小到大排序,然后寫入文件,然后從文件中讀取出來文件內容,然后反序,在追加到文件的下一行中
2. 分別把 string, list, tuple, dict寫入到文件中
#!/usr/bin/env python
#coding:utf8import 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 ldef wFile(l,mode):with codecs.open("testList.txt",'{0}b'.format(mode)) as fd:if mode == "a":fd.write('\n')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'}
?
轉載于:https://www.cnblogs.com/pythonlx/p/7756796.html
總結
以上是生活随笔為你收集整理的(三)3-1 练习的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。