Python讀寫遷移練習及注意事項

2021-10-10 16:17:03 字數 1627 閱讀 5121

已知成績如下: [『羅恩102\n』, 『哈利383\n』, 『赫敏570\n』, 『馬爾福275\n』]

對課堂上得到的「winner」文件再行處理一下。

讓學員的成績從高到低排列,然後放到新文件「winner_new.txt」。

# 下面已經為你準備好了開啟的**和一些變數名的準備。

# 請你完成資料處理以及新建文件(同乙個目錄)的**。

file1 =

open

('winner.txt'

,'r'

,encoding=

'utf-8'

) file_lines = file1.readlines(

) file1.close(

)dict_scores =

list_scores =

final_scores =

# print

(file_lines)

# print(len('\n'))

# 列印結果為:['羅恩102\n', '哈利383\n', '赫敏570\n', '馬爾福275\n']

# 經過測試,發現'\n'的長度是1。所以,名字是「第0位-倒數第5位」,分數是「倒數第4位-倒數第二位」。***

# 再根據「左取右不取」,可知:name-[:-4],score-[-4:-1]***

for i in file_lines:

# i是字串。

#print(i)

#print(len(i))

#得出的字串的長度:羅恩102 6 哈利383 6 赫敏570 6 馬爾福275 7

name = i[:-

4]# 取出名字(注:字串和列表一樣,是通過偏移量來獲取內部資料。)

score =

int(i[-4

:-1]

)# 取出成績

print

(name)

print

(score)

dict_scores[score]

= name # 將名字和成績對應存為字典的鍵值對(注意:這裡的成績是鍵)

#注意:可以通過鍵對值直接建立字典

#增加需乙個個增加,故需在迴圈裡增;

print

(list_scores)

list_scores.sort(reverse=

true

)# reverse,逆行,所以這時列表降序排列,分數從高到低。

print

(list_scores)

for i in list_scores:

result = dict_scores[i]

+str

(i)+

'\n'

print

(result)

print

(final_scores)

# 最終結果

winner_new =

open

('winner_new.txt'

,'w'

,encoding=

'utf-8'

) winner_new.writelines(final_scores)

winner_new.close(

)

python 檔案讀寫練習

練習包括 讀取與寫入 usr bin env python coding utf 8 time 2017 10 30 0030 08 58 file lianxi2.py 正向排序 import codecs l 1,5,3,8,2,4 l.sort 寫入檔案 with codecs.open 1....

python練習 讀寫檔案

對於不同的作業系統,檔案目錄會有不同,對於linux而言,萬事萬物皆檔案 對windows而言,檔案讀寫也很重要。import os 拼接路徑 os.path.join usr bin spam 返回路徑 usr bin spam 兩個倒斜槓等價於乙個正斜槓 獲得當前工作目錄 os.getcmd 相...

python讀寫檔案練習

1.請你通過檔案讀寫命令,讀取 photo1 裡的資料 提示見 區開頭 然後,新建名為 photo2 的 在同乙個資料夾 寫入讀到的資料。這樣,我們就通過檔案讀寫的 完成了的複製 而非滑鼠右鍵 with open photo2.png rb as file 以 rb 模式開啟 data file.r...