鱼C论坛

 找回密码
 立即注册
查看: 690|回复: 1

零基础35章第四题

[复制链接]
发表于 2019-3-20 06:01:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
各位大佬,小弟在做第四题时统计代码行数时,因为只学过python,所以只统计py文件。但是结果每次都是只能统计出第一个文件夹的文件,递归无法实现。请问这是为什么
代码如下
  1. import os
  2. import easygui as g

  3. def filesearch (filepath):   
  4.     f1 = os.listdir(filepath) ##打开初始文件夹##
  5.     count = 0 ##用于统计行数##
  6.     list1 = [] ##用于列出所有py文件名##
  7.     for each in f1:
  8.         if os.path.splitext(each)[1] == ".py":  ##若该文件是py 文件则打开文件,统计行数。##
  9.            
  10.             list1.append(filepath + "\" +each + " \n")
  11.             f = open (filepath+"\" +each, encoding='UTF-8')
  12.             for eachline in f:
  13.                 count = count +1
  14.             f.close()
  15.         if os.path.isdir(filepath + "\"+ each) :##若该文件文件夹,则用递归函数进入文件夹统计行数。##
  16.             
  17.             filesearch (filepath+ "\"+ each)
  18.             os.chdir(os.pardir)
  19.             return list1
  20.             return count
  21.     msg = "Total %s lines" % count + "Progress: " + str(count/1E6) +"\n There are " +\
  22.             str(1E6-count) + " lines left."
  23.     g.textbox(msg, "Final Results", list1) ##显示结果。##

  24. path = g.diropenbox()
  25. filesearch(path)
  26.    
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-3-20 06:04:16 | 显示全部楼层
不知为何:用代码功能发的时候,有的\\变成了\,我重新发一下。
import os
import easygui as g

def filesearch (filepath):   
    f1 = os.listdir(filepath) ##打开初始文件夹##
    count = 0 ##用于统计行数##
    list1 = [] ##用于列出所有py文件名##
    for each in f1:
        if os.path.splitext(each)[1] == ".py":  ##若该文件是py 文件则打开文件,统计行数。##
           
            list1.append(filepath + "\\" +each + " \n")
            f = open (filepath+"\\" +each, encoding='UTF-8')
            for eachline in f:
                count = count +1
            f.close()
        if os.path.isdir(filepath + "\\"+ each) :##若该文件文件夹,则用递归函数进入文件夹统计行数。##
            
            filesearch (filepath+ "\\"+ each)
            os.chdir(os.pardir)
            return list1
            return count
    msg = "Total %s lines" % count + "Progress: " + str(count/1E6) +"\n There are " +\
            str(1E6-count) + " lines left."
    g.textbox(msg, "Final Results", list1) ##显示结果。##

path = g.diropenbox()
filesearch(path)
   
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-14 17:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表