zoukankan      html  css  js  c++  java
  • 实例文件操作

    #把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
    
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # @time: 2017/10/30 19:45
    # Author: caicai
    # @File: sample01.py
    #import codecs
    import ast
    def listSort(a):
        b = sorted(a)
        return b
    
    def listReverse(file):
        a1 = file
        print(a1)
        for a2 in a1:
            a2 = list(ast.literal_eval(a2))
            a2.reverse()
            return a2
    
    
    def fileWrite(sort_list):
        f = open('2.txt','a')
        f.writelines(str(sort_list))
        f.writelines('
    ')
    
        f.close()
        return
    
    def fileRead():
        fd = open('2.txt')
        a2 = fd.readlines()
        fd.close()
        return a2
    
    if __name__ == '__main__':
        list1 = [2,32,43,453,54,6,576,5,7,6,8,78,7,89 ]
        list1_sort = listSort(list1)
        fileWrite(list1_sort)
        file_read = fileRead()
        file_read2 = listReverse(file_read)
        fileWrite(file_read2)
        print(fileRead())
    输出结果:
    ['[2, 5, 6, 6, 7, 7, 8, 32, 43, 54, 78, 89, 453, 576]
    ', '[576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]
    ']
    分别把string list tuple dict 写入文件中
    
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # @time: 2017/10/31 20:29
    # Author: caicai
    # @File: operation2.py
    ###########分别把string list tuple dict 写入文件中#########
    
    string = 'this si a string'
    list1 = ['hello','word','you']
    tuple1 = ('hello','word','you')
    dict1 = {'a':1,'b':2,'c':3}
    
    with open('3.txt','w') as fd:
        fd.write(string + '
    ')
        fd.write(str(list1) + '
    ')
        fd.write(str(tuple1) + '
    ')
        fd.write(str(dict1) + '
    ')
    
    with open('3.txt','r') as fd:
        a = fd.read()
        print(a)
    
    输出结果
    this si a string
    ['hello', 'word', 'you']
    ('hello', 'word', 'you')
    {'a': 1, 'b': 2, 'c': 3}
    

      

    不要让以后的自己被嫌弃
  • 相关阅读:
    hashcode() equals()
    Java7/8 HashMap ConcurrentHashMap
    mysql联合索引
    spring 事务传播
    SpringMVC Controller 单例 多例
    Java进阶 线程安全
    JVM—JVM内存模型
    jvm中堆和栈的区别
    spring boot springmvc视图
    springcloud eureka.instance
  • 原文地址:https://www.cnblogs.com/wxp997/p/7758144.html
Copyright © 2011-2022 走看看