- 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
l1 = [1, 23, 22, 5, 65]
l2 = sorted(l1)
with open('1.txt', 'wb') as fd:
l3 = [str(i) for i in l2]
str1 = ' '.join(l3)
fd.write(str1)
with open('1.txt', 'ab+') as fd:
content = fd.read()
l4 = [i for i in content.split(' ')]
print(l4)
l4.reverse()
str2 = ' '.join(l4)
print(str2)
- 分别把 string, list, tuple, dict写入到文件中
str1 = 'hello world'
list1 = ['a', 'b', 'c', 'd']
tuple1 = ('123', '456', 'abc', 'hhh')
dic1 = {'name': 'zhangsan', 'sex': 'M', 'age': 16}
with open('2.txt', 'ab+') as fd:
fd.write(str1 + '\n')
list2 = ' '.join(list1)
fd.write(list2 + '\n')
tuple2 = ' '.join(tuple1)
fd.write(tuple2 + '\n')
for k,v in dic1.items():
fd.write(k + ':' + str(v) + '\n')