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'}
  • 相关阅读:
    java HTTP代码示例
    eclipse创建文件package,source folder和folder区别及相互转换
    spring 及 spring boot 资源文件配置
    深入理解Java枚举类型(enum)
    Linux环境变量配置的三个方法--/etc/profile,~/.bashrc,shell
    JAXB和XStream比较
    java将配置信息写在数据库(利用反射)
    【大数据实战】Logstash采集->Kafka->ElasticSearch检索
    Linux 安装rabbitmq 遇到的一些问题
    Linux 下的jdk安装
  • 原文地址:https://www.cnblogs.com/pythonlx/p/7756796.html
Copyright © 2011-2022 走看看