1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
首先:将list 排序,其次写入文件
L=[10,8,3,2,6,0,1,9,5,4]L1=sorted(L)f=codecs.open('2.txt','wb')f.write(str(L1))f.write('\n')f.close()
文件结果:
[0, 1, 2, 3, 4, 5, 6, 8, 9, 10]
将文件内容读取,并反序,并追加。
with codecs.open('2.txt','ab+') as f1: L2=f1.read() L3=L2.strip(',').split(',') # print L3 L4=L3.reverse() f1.write(str(L4))
2. 分别把 string, list, tuple, dict写入到文件中
列出了string /list 写入文件中
#!/usr/bin/env python#!-*-coding:utf-8 -*-#!@Time :2017-11-02 下午 1:34#!@Author : yangyang#!@File : .pyimport codecswith codecs.open('3.txt','w+') as f: f.write('hello python\n') for i in xrange(1,10): f.write(str(i)) print ('\n') # dict1={'name':'yang','age':20} # for key,value in dict1.iteritems(): # f.write('key','value') # f.write({'name':'yang','age':20}) # print ('\n')
文件信息:
hello python123456789
将字典写入文件中:
dict1={'name':'yangyang','age':20}with codecs.open('3.txt','ab') as f1: for key in dict1.iteritems(): f1.write('\n') for value in key: f1.write(str(value))
文件内容如下:
hello python123456789age20nameyangyang
第二种方法:
with codecs.open('3.txt','wb') as f: dict1 = {'name': 'yscr', 'age': 20} for key, value in dict1.iteritems(): # f.write('{0},{1}'.format(key,value)) # f.write('{0},{1}'.format(key, value)) f.write('%s,%s' % (key, value)) f.write('\n') # f.write('%s,%s' % (key, value))
或者:with codecs.open('3.txt','wb') as f: dict1 = {'name': 'yscr', 'age': 20} for key, value in dict1.iteritems(): # f.write('{0},{1}'.format(key,value)) f.write('{0},{1}'.format(key, value)) # f.write('%s,%s' % (key, value)) f.write('\n') # f.write('%s,%s' % (key, value))
文件内容:
age,20name,yscr