zoukankan      html  css  js  c++  java
  • python 复习-2

    把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件件内容,然后反序,再追加到文件的下一行中

    """把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件件内容,然后反序,再追加到文件的下一行中"""
    import codecs
    
    list1 = [32, 43, 12, 10, 5, 100, 120 ,110 ,119, 300, 250]
    
    # list从小到大排序
    list1.sort()
    
    # 将list写入文件
    with codecs.open('Exercise.txt', 'wb') as file1:
        for i in xrange(0, len(list1)):
            file1.write(str(list1[i]))
            if i != len(list1) - 1:
                file1.write(',')
    
    # 从文件读取内容,并反序
    with codecs.open('Exercise.txt') as file1:
        text = file1.read()
    text_list = text.strip(',').split(',')
    text_list.reverse()
    
    # 将结果追加到文件下一行中
    with codecs.open('Exercise.txt', 'ab') as file1:
        file1.write('
    ')
        for i in xrange(0, len(text_list)):
            file1.writelines(str(text_list[i]))
            if i != len(text_list) - 1:
                file1.write(',')
    

    执行后文件内容:

    5,10,12,32,43,100,110,119,120,250,300
    300,250,120,119,110,100,43,32,12,10,5
    
    

    分别把string list tuple dict 写入到文件中

    """分别把string list tuple dict 写入到文件中"""
    
    string = 'This is a string'
    list1 = ['This', 'is', 'a', 'list']
    tuple1 = ('This', 'is', 'a', 'tuple')
    dict1 = {'This':'is', 'a':'dict'}
    
    
    with codecs.open('Exercise.txt', 'wb') as ff:
        ff.write(string + '
    ')
        ff.write(str(list1) + '
    ')
        ff.write(str(tuple1) + '
    ')
        ff.write(str(dict1) + '
    ')
        ff.write('##' * 20 + '
    ')
    
        ff.write(string + '
    ')
    
        for i in xrange(0, len(list1)):
            ff.write(list1[i] + ' ')
        ff.write('
    ')
    
        for i in xrange(0, len(tuple1)):
            ff.write(tuple1[i] + ' ')
        ff.write('
    ')
    
        for key, values in dict1.iteritems():
            ff.write(key +  ' ' + values + ' ')
        ff.write('
    ')
    

    写入的文件内容:

    This is a string
    ['This', 'is', 'a', 'list']
    ('This', 'is', 'a', 'tuple')
    {'This': 'is', 'a': 'dict'}
    ########################################
    This is a string
    This is a list 
    This is a tuple 
    This is a dict 
    
    
  • 相关阅读:
    简易仿ios菊花加载loading图
    android 仿微信表情雨下落!
    android view 转Bitmap 生成截图
    设计模式——享元模式
    虚拟内存技术原理解析
    读史——回望勾吴
    android日志搜集原理及方案比较
    java四种引用及在LeakCanery中应用
    读史——秦历史概况
    git使用总结
  • 原文地址:https://www.cnblogs.com/lijunjiang2015/p/7758095.html
Copyright © 2011-2022 走看看