Python:统计特定文件夹中,特定文件代码行数的小程序

最近自己在帮朋友做一个外贸管理系统项目,哼哧哼哧弄了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();




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值