python变量作用域问题

import os

SYSTEMList = ["System", "SYSTEM", "system", "windows", "Windows", "WINDOWS"]
def getTheTargetDisk():
    """ 
    Get the scanner 
    return: the input string
    """
    input = raw_input("-->Disk: ")
    return input

def theLevelIndex(root):
    """ 
    Find the root's level
    root: string, the index you want to judge
    return: int, 0 for A, 1 for B
    """
    if os.path.isdir(root):
        for filepath in os.listdir(index):
            if  os.path.isfile (filepath):
                return 1
    return 0



root = getTheTargetDisk()
rootlist = os.listdir(root)
listA = []
listB = []
for dirpath in rootlist:
    for sysName in SYSTEMList:
        if sysName in dirpath:#Error:'dirpath' is not defined
            del dirpath
for dirroot in rootlist:
    if os.path.isdir(dirroot):
        if theLevelIndex(dirroot) == 0:
            listA.append(root + dirroot)
        else:
            listB.append(root + dirroot)
print listA
print listB

如上的代码,在运行至if sysName in dirpath时,显示dirpath未定义
请问下这是为什么?if中调用的dirpath不是在最外层的for循环中吗?
图片描述

阅读 2.9k
3 个回答
for i in [1, 2, 3]:
    del i
    print i

del之后就把变量从当前作用域里删除了

试试rootlist.remove(i)

for dirpath in rootlist:
   for sysName in SYSTEMList:
       if sysName in dirpath:#Error:'dirpath' is not defined
           del dirpath

其实我感觉能一行搞定
rootlist = [i for i in rootlist if set(SYSTEMList).intersection(set(i)).__len__() == 0]

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进