lfc990426 发表于 2021-11-15 14:22:26

python 30 课后作业

import os
import os.path
def find_file(file_path,file_name):
   os.chdir(file_path)
   os.listdir(file_path)

   for each_one in os.listdir(file_path): #对于输入路径中的二级目录中的所有文件   
          if file_name == each_one:         #如果路径文件下的二级目录中存在需要找的文件
               print(file_path + file_name)
          else:
               find_file(each_one,file_name)#如果二级目录中没有,需要在二级目录下的三级目录中找
               os.chdir(os.pardir)
file_path = input('请输入待查找的初始目录:')
file_name = input('请输入待查找问价的名字:')
find_file(file_path,file_name)
               








{:9_228:} {:9_221:}
大佬们,代码该怎么改

myqf123 发表于 2021-11-15 15:06:54

本帖最后由 myqf123 于 2021-11-15 15:48 编辑

你这程序没有进行文件和目录文件判断,对于既不是你要找的文件,也不是单纯的目录文件,你的程序是无法识别的,比如你的目录下第一个文件是:1.py,它既不是你要找的文件,但又不是目录文件,而你的程序会把这个文件当做路径传递给自身,自然会引起错误。

jackz007 发表于 2021-11-15 15:09:49

本帖最后由 jackz007 于 2021-11-15 15:30 编辑

#coding:gbk

import os

def find_file(file_path , file_name):
    c = 0
    try:
      for each_one in os . listdir(file_path):
            x = os . path . join(file_path , each_one)
            if os . path . isfile(x):
                if each_one . lower() == file_name . lower():
                  print(x)
                  c += 1
            elif os . path . isdir(x):
                c += find_file(x , file_name)
    except Exception as e:
      pass
    return c

file_path = input('请输入待查找的初始目录 : ')
file_name = input('请输入待查找文件的名字 : ')
print('一共找到了 %d 个目标文件.' % find_file(file_path , file_name))
      运行实况:
D:\0002.Exercise\Python>python x.py
请输入待查找的初始目录 : C:\
请输入待查找文件的名字 : notepad.exe
C:\Windows\notepad.exe
C:\Windows\System32\notepad.exe
C:\Windows\SysWOW64\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7600.16385_none_9ebebe8614be1470\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7601.18917_none_a0f2c3fc11a9f24c\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7601.23120_none_a16a66f72ad62fe8\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7600.16385_none_cb0f7f2289b0c21a\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.18917_none_cd438498869c9ff6\notepad.exe
C:\Windows\winsxs\amd64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.23120_none_cdbb27939fc8dd92\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7600.16385_none_d5642974be118415\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.18917_none_d7982eeabafd61f1\notepad.exe
C:\Windows\winsxs\wow64_microsoft-windows-notepad_31bf3856ad364e35_6.1.7601.23120_none_d80fd1e5d4299f8d\notepad.exe
一共找到了 12 个目标文件.

D:\0002.Exercise\Python>
页: [1]
查看完整版本: python 30 课后作业