學習筆記(10月30~31日)——複習&練習

三週一次課(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 codecs
string = "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 codecs
list1 = ["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())

結果:

ni
hao
ma


2.3把tuple寫入到文件中

import codecs
tuple1 = ("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 codecs
dict1 = {"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: 20
name: wan yang
height: 175


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章