# 自己寫過的程序,統計一下你寫過多少行代碼。包括空行和注釋,但是要分別列出來
1.打開文件方法
1.1 以讀文件的模式打開一個文件對象,使用Python內置的open()函數,傳入文件名和標示符
open()函數,傳入文件名和標示符f = open('/Users/michael/test.txt', 'r')
1.2 Python引入了with語句來自動幫我們調用close()方法
with open('/path/to/file', 'r') as f: print(f.read())
1.3 調用readline()可以每次讀取一行內容,調用readlines()一次讀取所有內容並按行返回list
for line in f.readlines(): print(line.strip()) # 把末尾的'\n'刪掉
2.python計算文件行數的三種方法
def linecount_1(): return len(open('data.sql').readlines())#最直接的方法 def linecount_2(): count = -1 #讓空文件的行號顯示0 for count,line in enumerate(open('data.sql')): pass #enumerate格式化成了元組,count就是行號,因為從0開始要+1 return count+1 def linecount_3(): count = 0 thefile = open('data.sql','rb') while 1: buffer = thefile.read(65536) if not buffer:break count += buffer.count('\n')#通過讀取換行符計算 return count
3.Python strip() 方法用於移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。
stip()方法語法:
str.strip([chars]);
4.startswith() 方法用於檢查字符串是否是以指定子字符串開頭,如果是則返回 True,否則返回 False。如果參數 beg 和 end 指定值,則在指定范圍內檢查
startswith()方法語法:
str.startswith(substr, beg=0,end=len(string))
完整代碼:
# conding:utf-8
count = 0 sum = 0 catalog = open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py") t = len(open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py").readlines()) #統計行數 for line in catalog.readlines(): line = line.strip() #去掉每行頭尾空白 print(line) if line == "": count += 1 if line.startswith("#"): #startswith() 方法用於檢查字符串是否是以指定子字符串開頭,如果是則返回 True,否則返回 False sum += 1 print("統計的文件行數為:%d行" %t) print("統計文件的空行數為:%s" %count) print("統計的注釋行數為:%s" %sum)
