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('\n')
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 + '\n')
ff.write(str(list1) + '\n')
ff.write(str(tuple1) + '\n')
ff.write(str(dict1) + '\n')
ff.write('##' * 20 + '\n')
ff.write(string + '\n')
for i in xrange(0, len(list1)):
ff.write(list1[i] + ' ')
ff.write('\n')
for i in xrange(0, len(tuple1)):
ff.write(tuple1[i] + ' ')
ff.write('\n')
for key, values in dict1.iteritems():
ff.write(key + ' ' + values + ' ')
ff.write('\n')
写入的文件内容:
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