【问题标题】:Python, function output not as expectedPython,函数输出不符合预期
【发布时间】:2014-09-22 03:01:28
【问题描述】:

我写了一个函数来在 python 中创建一个目录。如果已使用原始名称,则该函数将扩展名(例如 _1)添加到目录名称。 该功能按预期工作并创建文件夹;但是返回值有问题。当我打印出来时,我没有。这是我的代码。可能不是最干净的:s。这与在函数内部调用自身有关,但我不确定如何解决。

import os


##function to generate a dir with extension if it already exists
def createDir(directory,ext):
  thePath=directory+ext
  if not os.path.exists(thePath):
    os.makedirs(thePath)
    output=thePath + '/'
    print 'I return ' + output #I got "I return /media/usb0/incomplete_noNameYet_2/ (Because incomplete_noNameYet and incomplete_noNameYet_1 already existed)" This is fine!
    return output
  else:
    if ext =='':
      ext='_1'
    else:
      ext= '_' + str(int(ext[1:len(ext)])+1)
    createDir(directory,ext)

def main():
  print createDir('/media/usb0/incomplete_noNameYet','') #I got none.   

if __name__ == '__main__':
  main() 

【问题讨论】:

    标签: python recursion directory


    【解决方案1】:

    问题是在 else 分支上,您调用 createDir 并没有返回值。对 createDir 的初始调用执行后两个递归调用(包括它们的副作用),但随后丢弃返回值并返回 None。

    【讨论】:

      【解决方案2】:

      你忽略了递归调用的返回值;在那里也添加一个return

      return createDir(directory,ext)
      

      否则createDir()的返回值将被丢弃,并且父函数调用返回没有显式的return调用,默认为None

      【讨论】:

        猜你喜欢
        • 2021-10-04
        • 2022-01-16
        • 2017-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多