代碼如下:
#!/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
運行結果如下:
對齊很坑的。
fileobj = open(filename,mode) obj.read() obj.readline() obj.readlines()
文件的讀就是上面三個,第一個,默認讀取所有內容,第二個讀取一行,第三個讀取所有行。可循環遍歷每行的內容。
讀書和健身總有一個在路上