• (三)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'}
  • 相关阅读:
    EMIF接口的寻址问题
    C6000系类的内联函数
    C6000代码层面优化(一)
    RHCE学习笔记
    找出并关闭Ruby On Rails进程.
    Rails4添加bootstrap支持
    如何删除gnome3面板上的图标?
    出现 ruby cannot load such file -- zlib 问题的解决方法
    Debian安装软件时提示插入光盘
    Debian7桌面屏蔽图标和右键菜单的解决方法。
  • 原文地址:https://www.cnblogs.com/pythonlx/p/7756796.html
Copyright © 2020-2023  润新知