Discuss / Python / 第二题

第二题

Topic source

南小i

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/python3

import os

def joinpath(cdir, s = ''):	#Define the function to add the path because the abspath doesn't show the parent folder
	new_path = os.path.join(cdir, s)
	return new_path


def myfind(cdir = '.'):	#Find the item in every folders
	myitem = item
	my_path = joinpath(os.path.abspath(cdir))
	for x in os.listdir(cdir):
		if myitem in x and os.path.splitext(x)[1] != '':
			print(joinpath(my_path, x))
		elif os.path.splitext(x)[1] == '':
			my_path = joinpath(my_path, x)
			return myfind(x)
	return

def myfind2(cdir = '.'):	#Find the item in every folders without filename extension
	myitem = item
	print(myitem)
	my_path = joinpath(os.path.abspath(cdir))
	for x in os.listdir(cdir):
		if myitem in os.path.splitext(x)[0] and os.path.splitext(x)[1] != '':
			print(joinpath(my_path, x))
		elif os.path.splitext(x)[1] == '':
			my_path = joinpath(my_path, x)
			return myfind(x)
	return

if __name__ == '__main__':
	
	#search the current dir
	item = str(input('Please enter what you\'d like to search:')) 	#Define the item that we want to search

	judge = str(input('Do you want to include the filename extension? Y/N:'))
	if judge == 'Y' or judge == 'y':
		myfind()
	elif judge == 'N' or judge == 'n':
		myfind2()
	else:
		raise ValueError('Please enter the right command')

这段代码找不到某些文件。。例如目录下面有两个hello.py和convert lifespan.py的文件,找不到,但是其他文件都没问题。

但是在交互模式一行一行试的时候没问题,不知道是什么原因,很难受

南小i

#2 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/python3

import os

def joinpath(cdir, s = ''):	#Define the function to add the path because the abspath doesn't show the parent folder
	new_path = os.path.join(cdir, s)
	return new_path


def myfind(cdir = '.', file_path = os.path.abspath('.')):	#Find the item in every folders
	myitem = item
	my_path = joinpath(os.path.abspath(cdir))
	for x in os.listdir(cdir):
		if myitem in x and os.path.splitext(x)[1] != '':
			print(joinpath(file_path, x))
		elif os.path.splitext(x)[1] == '':
			my_path = joinpath(my_path, x)
			myfind(x, my_path)

def myfind2(cdir = '.', file_path = os.path.abspath('.')):	#Find the item in every folders without filename extension
	myitem = item
	my_path = joinpath(os.path.abspath(cdir))
	for x in os.listdir(cdir):
		if myitem in os.path.splitext(x)[0] and os.path.splitext(x)[1] != '':
			print(joinpath(file_path, x))
		elif os.path.splitext(x)[1] == '':
			my_path = joinpath(my_path, x)
			myfind2(x, my_path)

if __name__ == '__main__':
	
	#search the current dir
	item = str(input('Please enter what you\'d like to search:')) 	#Define the item that we want to search

	judge = str(input('Do you want to include the filename extension? Y/N:'))
	if judge == 'Y' or judge == 'y':
		myfind()
	elif judge == 'N' or judge == 'n':
		myfind2()
	else:
		raise ValueError('Please enter the right command')

解决了,不该写return,不然在进入子文件夹的时候循环就结束了

想写递归,结果脑子没想清楚,弄了个四不像,还是之前的函数式编程没理解透彻


  • 1

Reply