python核心编程学习笔记-2016-08-03-01-习题9-9

来源:互联网 发布:java sql update 编辑:程序博客网 时间:2024/05/18 16:54

习题9-9

一开始打算导入各个模块,再利用__doc__属性,但是感觉不是太好。浏览了网上的一些答案,发现他们都是利用打开文件,直接遍历文件内容,查找两个三引号"""之间内容的思路,因此参考了这一思路,写了代码。

#-*-coding: utf-8-*-import ospath = r'c:\python27\Lib'os.chdir(path)files = []for i in os.listdir(path):    if i[-3:] == '.py':        files.append(i)have_doc_file = {}none_doc_file = []for file in files:    f = open(file, 'r')    has_doc = False    doc = []    for eachLine in f:        if eachLine[:3] == '"""' and not has_doc: # 以"""开头的行,首先确定有文档字符串            has_doc = True        if has_doc:            doc.append(eachLine)        if eachLine[-4:-1] == '"""' and has_doc: # 结尾字符串是"""\n,不要漏掉\n            break    f.close()    if has_doc:         have_doc_file[file] = ''.join(doc)    else:        none_doc_file.append(file)f_has_doc_obj = open(r'e:\Learning_python\coreprogramming\has_doc.txt', 'w')for k, v in have_doc_file.iteritems():    f_has_doc_obj.write(k + '\n' + v + '\n')f_has_doc_obj.close()f_none_doc_obj = open(r'e:\Learning_python\coreprogramming\none_doc.txt', 'w')for i in none_doc_file:    f_none_doc_obj.write(i + '\n')f_none_doc_obj.close()


0 0