zoukankan      html  css  js  c++  java
  • (三)3-1 练习

    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'}
  • 相关阅读:
    xml学习_上篇
    回首博客 年满一周年,记录90个点滴瞬间
    编写PHP代码总结
    代码高亮插件SyntaxHighlighter
    记忆,是一座沙城!
    dreamweaver中的 map怎么调用?_制作热点图像区域
    手机端rem如何适配_rem详解及使用方法
    彻底弄懂css中单位px和em,rem的区别
    JavaScript学习方法
    10条建议让你创建更好的jQuery插件
  • 原文地址:https://www.cnblogs.com/pythonlx/p/7756796.html
Copyright © 2011-2022 走看看