|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目要求是这样的:编写一个程序,用户输入文件名以及开始搜索的路径,搜索该文件是否存在。如遇到文件夹,则进入文件夹继续搜索
然后我自己写的代码如下,还没看答案。。
import os,os.path
def finds(file,user_path):
while True:
for each_file in os.listdir(path=user_path):
if file in os.listdir(path=user_path):
print('该文件在%s下存在'% user_path)
elif os.path.isdir(os.path.join(user_path,each_file)) == True:
user_path = os.path.join(user_path,each_file)
finds(file,user_path)
break
break
file = input('请输入要查找的文件名:')
user_path = input('请输入要查找的文件夹:')
finds(file,user_path)
现在的问题是只能找一层,碰到文件夹进不去。应该是elif哪里出问题了,求助一下!!
改成这样即可:
- import os
- def finds(file, user_path):
- for each_file in os.listdir(path=user_path):
- if file == each_file:
- print('该文件在%s下存在.' % user_path)
- elif os.path.isdir(os.path.join(user_path, each_file)):
- user_path = os.path.join(user_path, each_file)
- finds(file, user_path)
- user_path = user_path[::-1].split('\\',1)[1][::-1]
- file = input('请输入要查找的文件名:')
- user_path = input('请输入要查找的文件夹:')
- finds(file, user_path)
复制代码
|
|