python文件讀寫的基礎使用(計算總評成績)


代碼如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

tfile = open("文件讀寫","r+",encoding='UTF-8')
#fileobj = open(filename,mode)
#rwax + t文本文件、b二進制文件

#讀
# r1 = tfile.read()
# print(r1)
head = tfile.readline()
newhead = head[0:-1]+''+'  總評成績'
print(newhead+'\n')


for line in tfile.readlines():
    l = line.split()
    s = round(int(l[3])*0.5+int(l[4])*0.25+int(l[5])*0.25,2)
    print('      '.join(l)+'  '+str(s))

tfile.close()

操作文件:

學號		姓名	 專業	  筆試	  平時	  實驗
2050921010	張三	數學	65	85	75
2050921011	李四	英語	86	95	98
2050921012	白起	化學	86	95	88
2050921014	亞瑟	材料	62	75	76
2050921015	妖姬	大氣	87	88	98
2050921016	蓋倫	電腦	86	78	78

運行結果如下:

image

對齊很坑的。

fileobj = open(filename,mode)
obj.read()
obj.readline()
obj.readlines()

文件的讀就是上面三個,第一個,默認讀取所有內容,第二個讀取一行,第三個讀取所有行。可循環遍歷每行的內容。


讀書和健身總有一個在路上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM