实例文件操作

#把一个数字的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('\n')

    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]\n', '[576, 453, 89, 78, 54, 43, 32, 8, 7, 7, 6, 6, 5, 2]\n']

 

分别把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 + '\n')
    fd.write(str(list1) + '\n')
    fd.write(str(tuple1) + '\n')
    fd.write(str(dict1) + '\n')

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}

  

转载于:https://www.cnblogs.com/wxp997/p/7758144.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值