最近自己在帮朋友做一个外贸管理系统项目,哼哧哼哧弄了2个月,写了一大堆的java代码,还有xhtml文件,处于对自己成就感满足的需求,打算写个程序统计一下目前总共的代码行数,正好最近在学习Python程序,于是实现的语言选择了Python,由于自己是新手,所以写的不足的地方还请指点
程序如下(统计特定目录下,java文件的行数):
'''
count file lines number by directory
@author: aihua.sun
'''
import os.path;
# -*- coding: utf-8 -*-
import os;
import string;
import codecs;
resultFile = open("result.file", "w+");
DOC_TAG = "'''";
FILE_COUNT = 0;
FILE_EXTENSION = ".java";
LINE_NUMBER = 0;
COUNT_LINE_NUMBER = True;
DEFAULT_DIR = "D:\sourcecode\FTS";
def collection():
dirpath = input("please input module directionary:");
if os.path.isdir(dirpath):
walkTree(dirpath);
else:
print("please input a directionary path!");
#use default directory
dirpath = DEFAULT_DIR;
walkTree(dirpath);
print("DIRECTOTY:%s FILE_EXTENSION:%s LINE_NUMBER:%s" % (dirpath, FILE_EXTENSION, LINE_NUMBER))
def walkTree(dirpath):
os.chdir(dirpath);
fileExtensionLen = len(FILE_EXTENSION);
for subFile in os.listdir(dirpath):
#print(os.getcwd());
if os.path.isdir(subFile):
fullSubFile = str(os.getcwd()) + str(os.sep) + subFile;
#print(fullSubFile);
walkTree(fullSubFile);
elif os.path.basename(subFile)[-fileExtensionLen:] == FILE_EXTENSION:
collectDocument(subFile);
os.chdir(os.path.pardir);
def collectDocument(subFile):
countDirectoryLineNumber(subFile)
resultFile.writelines("\n" + "FILE: %s%s%s" % (str(os.getcwd()), str(os.sep), str(os.path.basename(subFile))));
resultFile.writelines("\n" + "DOCUMENT:");
appendDocToResultFile(subFile, resultFile);
def countDirectoryLineNumber(subFile):
#print(subFile)
global LINE_NUMBER;
#use "w+" will write clear target file, so it's dangerous
open = codecs.open;
newFileObject = open(subFile, "r+", 'utf-8');
singleFileLineNumber = len(newFileObject.readlines());
#print(singleFileLineNumber);
LINE_NUMBER += singleFileLineNumber;
def appendDocToResultFile(subFile, resultFile):
inDocArea = False;
for fileLine in subFile:
#begin with document
if fileLine.find(DOC_TAG) > 0:
inDocArea = True;
if inDocArea:
resultFile.writelines(fileLine);
#end of document
if inDocArea and fileLine.find(DOC_TAG) > 0:
resultFile.writelines(fileLine);
resultFile.close();
break;
if __name__ == '__main__':
collection();