描述
打印輸出附件文件的有效行數,注意:空行不計算為有效行數。
輸入輸出示例
這是僅給出輸出格式樣例,不是結果。
我的代碼:
1 f = open("latex.log","r").readlines() 2 counts = 0 3 for line in f : 4 line =line.strip('\n') 5 if len(line)!= 0: 6 counts += 1 7 else: 8 continue 9 print("{}".format(counts))
1 f = open("latex.log","r").readlines() 2 counts = 0 3 for i in range(0,len(f)) : 4 f[i] =f[i].strip('\n') 5 if len(f[i])!= 0: 6 counts += 1 7 else: 8 continue 9 print("共{}行".format(counts))
老師給出的參考代碼:
1 f = open("latex.log") 2 s = 0 3 for line in f: 4 line = line.strip('\n') 5 if len(line) == 0: 6 continue 7 s += 1 8 print("共{}行".format(s))
試了半天,但轉了一圈發現自己是忘了加“共和行”兩個字。
但根本原因是自己語法不扎實,這道題我的收獲如下:
1、首先是 for in 的問題,
for in 說明:也是循環結構的一種,經常用於遍歷字符串、列表,元組,字典等
格式:

執行流程:x依次表示y中的一個元素,遍歷完所有元素循環結束。這道題里line可循環列表
2、readlines() 、read()、和for in循環文件逐行讀取問題
readlines()讀取全部文件,返回list形式,帶有\n換行符
read()次性讀取文件全部內容,當成一個字符串處理,返回類型為字符串
for line in fh 將文件對象 fh 視為可迭代的,什么是可迭代的我現在也不知道~
3、意外收獲:
Python引入了with
語句來自動幫我們調用close()
方法:
1 with open('/path/to/file', 'r') as f: 2 print(f.read())
但是代碼更佳簡潔,並且不必調用f.close()
方法。