Python 30讲文件系统 课后作业2
import osdef searchfile(path,name):
for each in os.listdir(path):
#print(each)
if each==name:
print(os.getcwd()+os.sep+name)
if os.path.isdir(each):
#print('\n next-> \n')
searchfile(each,name)
path='E:\\'
name='name.txt'
if os.path.exists(path):
searchfile(path,name)
else:
print('no!')
我的代码运行之后,永远不会递归(测试用的 next-> 没有输出),请问为什么? import os
def searchfile(path,name):
for each in os.listdir(path):
if each==name:
print(os.path.join(path,each))
if os.path.isdir(os.path.join(path,each)):
#print('\n next-> \n')
searchfile(os.path.join(path,each),name)
path='E:\\图片'
name='name.txt'
if os.path.exists(path):
print('path yes')
searchfile(path,name)
else:
print('no!')
已解决,问题在于isdir()所需参数需要绝对路径 import os
def fun (path, file_name):
for each in os.listdir(path):
each_path = os.path.join(path, each)
if os.path.isfile(each_path):
if file_name == each:
print(each_path)
else:
fun(each_path, file_name)
path = input('请输入待查找的初始目录:')
file_name = input('请输入需要查找的目标文件:')
fun(path, file_name)
Archer伽美什 发表于 2021-5-17 23:47
import os
def searchfile(path,name):
for each in os.listdir(path):
在for语句前面加一句 path = os.curdir 就可以在输入的时候不用绝对路径
页:
[1]