求指点python递归

import os

class My_IO:
fileName=""
def __init__(self,fileName="test.txt"):
self.fileName=fileName
if os.path.isfile(self.fileName):
print("You are trying to create a file "+ self.fileName +" that already existed!")
else:
print(fileName + " is not existed!")
a=open(self.fileName,"w")
a.close()

def split_path(self, path=""):
if path == "":
path=os.getcwd()
path=path + "\\" + self.fileName
parent_path, name=os.path.split(path)
return (parent_path, name)

def split_fully(self):
parent_path, name=self.split_path()
if name == "":
return (parent_path, )
else:
print self.split_path(parent_path) + (name, )

f=My_IO("linh.txt")
print("split: ")
print(f.split_path())
print("split fully: ")
f.split_fully()
=======================
输出结果怎么是这样的?
split:
('C:\\Users\\Lin\\workspace\\python_io\\src', 'linh.txt')
split fully:
('C:\\Users\\Lin\\workspace\\python_io', 'src', 'linh.txt')

我以为是('C:\\','Users','Lin','workspace',‘python_io', 'src', 'linh.txt'),哪里写错了?
谢谢

看了你的代码,你这里面是没有用到递归的

至于你的输出,f.split_path()输出的是('C:\\Users\\Lin\\workspace\\python_io\\src', 'linh.txt'),那是因为你在split_path()里的处理时这样的,因为os.path.split是将完整路径分隔成路径和文件名。你这里先合起来,再分隔,没太搞懂是要做什么。我给你做下注释

path=path + "\\" + self.fileName   #'C:\\Users\\Lin\\workspace\\python_io\\src' + 'linh.txt'
parent_path, name=os.path.split(path) # parent_path='C:\\Users\\Lin\\workspace\\python_io\\src'

#name= 'linh.txt'

return (parent_path, name)

在split_fully()函数里,你调用了两次split_path(),第一次返回的parent_path再一次执行了os.path.split,它将你的路径再从最后切了一个'src'出来,


我这里只是打印了一下,你可以插入到列表或作其他处理。看看你的需求是不是这个样子:

path = 'C:\\Users\\Lin\\workspace\\python_io\\src\\linh.txt'
def getsinglepath(path):
path,singlepath = os.path.split(path)
if singlepath == '':
return ''
else:
print singlepath
return getsinglepath(path)
getsinglepath(path)

>>> getsinglepath(path)

linh.txt

src

python_io

workspace

Lin

Users

''

温馨提示:答案为网友推荐,仅供参考
相似回答