三周一次课(10月30日)、三周二次课(10月31日)
复习上周的内容
要求如下:
1. 把一个数字的list从小到大排序,然后写入文件,然后从文件中读取出来文件内容,然后反序,在追加到文件的下一行中
list1 = [1, 2, 33, 50, 78, 99, 4, 83, 43, 111]list1.sort()
with codecs.open('test.txt', 'wb') as file1:
file1.write(str(list1))
with codecs.open('test.txt', 'rb') as file2:
list2 = file2.read()
list2 = eval(list2)
with codecs.open('test.txt', 'ab') as file2:
list2.reverse()
str2 = ('\n' + str(list2))
file2.write(str2)
结果:
[1, 2, 4, 33, 43, 50, 78, 83, 99, 111][111, 99, 83, 78, 50, 43, 33, 4, 2, 1]
2、分别把 string, list, tuple, dict写入到文件中
2.1把string写入到文件中
import codecsstring = "hello world!"with codecs.open('test.txt', 'wb') as file1: file1.write(string)with codecs.open("test.txt", "rb") as file1: print(file1.read())
结果:
hello world!
2.2把list写入到文件中
import codecslist1 = ["ni\n", "hao\n", "ma\n"]with codecs.open('test.txt', 'wb') as file1: file1.writelines(list1)with codecs.open("test.txt", "rb") as file1: print(file1.read())
结果:
nihaoma
2.3把tuple写入到文件中
import codecstuple1 = ("ni", " hao", " ma", "?")with codecs.open('test.txt', 'wb') as file1: file1.writelines(tuple1)with codecs.open("test.txt", "rb") as file1: print(file1.read())
结果:
ni hao ma?
2.4把dict写入到文件中
import codecsdict1 = {"name": "wan yang", "age": "20", "height": "175"}with codecs.open('test.txt', 'wb') as file1: for i in dict1.iterkeys(): file1.write(i + ": "+dict1.get(i)+"\n")with codecs.open("test.txt", "rb") as file1: print(file1.read())
结果:
age: 20name: wan yangheight: 175