python 2.7 os.path.isdir(unicode abspath string)什么都不返回

时间:2015-02-10 13:58:55

标签: python unicode directory

我正在尝试在os.listdir输出中找到文件夹。但是,os.path.isdir在该列表中具有unicode目录的面时,u'\u0130letildi'中没有返回名为self.file_list的目录。所以我无法从listdir中弹出该目录。

示例代码正在使用ipython控制台,但是我的项目。

import os
a = os.path.expanduser(u"~")  # this creates unicode absolute user path var.
b = "Documents\\Gelen Fax"    # this is the base folder that I try to use files in it
c = os.path.join(a, b)        # output is: u'C:\\Users\\user\\Documents\\Gelen Fax'
l = os.listdir(c)
# can print list of the unicode file names:
# [u'02163595310_20141114_001406.pdf',
#  u'Thumbs.db',
#  u'Yedek',
#  u'\u0130letildi']

列表中的最后一个对象几天来就令人头疼。

for x in l:
    print(type(os.path.join(c,x)), os.path.join(c,x), os.path.isdir(os.path.join(c,x)))

(<type 'unicode'>, u'C:\\Users\\user\\Documents\\Gelen Fax\\02163595310_20141114_001406.pdf', False)
(<type 'unicode'>, u'C:\\Users\\user\\Documents\\Gelen Fax\\Thumbs.db', False)
(<type 'unicode'>, u'C:\\Users\\user\\Documents\\Gelen Fax\\Yedek', True)
(<type 'unicode'>, u'C:\\Users\\user\\Documents\\Gelen Fax\\\u0130letildi', True)

到目前为止一切正常,但是当我把它放在我的项目中时它会开始失败。当我调用GetFileList().filtered_list()时,在运行u'\u0130letildi'方法时没有文件夹exclude_directories()的跟踪。但是,它在self.file_list到达时可用:

log.debug(self.file_list)
for f in self.file_list:
    log.debug("%s - %s - %s" % (repr(type(f)), repr(f), repr(os.path.isdir(f))))
    if os.path.isdir(f):
         self.file_list.pop(self.file_list.index(f))

上面的日志输出是:

[u'C:\\Users\\user\\Documents\\Gelen Fax\\02163595310_20141114_001406.pdf', u'C:\\Users\\user\\Documents\\Gelen Fax\\Thumbs.db', u'C:\\Users\\user\\Documents\\Gelen Fax\\Yedek', u'C:\\Users\\user\\Documents\\Gelen Fax\\\u0130letildi']

<type 'unicode'> - u'C:\\Users\\user\\Documents\\Gelen Fax\\02163595310_20141114_001406.pdf' - False
<type 'unicode'> - u'C:\\Users\\user\\Documents\\Gelen Fax\\Thumbs.db' - False
<type 'unicode'> - u'C:\\Users\\user\\Documents\\Gelen Fax\\Yedek' - True 

如上所示,u'\u0130letildi'目录在列表日志中可用。但是当列表迭代for循环时没有任何痕迹。

这是我的课程:

class FSTools():
    """
    File System Tools Class
    create_directory: Creates directory in given path
    control_directory: Checks directory existence in given path
    safe_make_directory: Cehcks directory existence before make
    user_path: Returns current user home directory path
    target_dir_path: Returns given target directory full path under current user
    """
    def __init__(self, directory=None):
        if directory is None:
            raise Exception(u"No directory name or path given.")
        self.directory = directory

    @property
    def user_path(self):
        return os.path.expanduser(u"~")

    def target_dir_path(self):
        return os.path.join(self.user_path, self.directory)

    def make_directory(self):
        created = False
        try:
            os.makedirs(self.target_dir_path())
            created = True
        except Exception as e:
            log.exception(e.message)
        finally:
            return created

    def check_directory(self):
        return os.path.exists(self.target_dir_path())

    def safe_make_directory(self):
        if not self.check_directory():
            if not self.make_directory():
                raise Exception(u"Unable to create directory: <<{directory}>>".format(directory=self.directory))
            else:
                log.info(u"Directory created: <<{directory}>>".format(directory=self.directory))
        else:
            log.warning(u"Directory exsists: <<{directory}>>".format(directory=self.directory))

class GetFileList():
    """
    Returns files list in given target directory
    """
    def __init__(self):
        self.fstools = FSTools(SETTINGS["target_directory"])
        self.target_dir = self.fstools.target_dir_path()
        log.info("Getting file list in {target}".format(target=self.target_dir))
        self.file_list = os.listdir(self.target_dir)
        self.file_list = [os.path.join(self.target_dir, f) for f in self.file_list]
        self.exclude_directories()
        self.exclude_files()

    def exclude_directories(self):
        try:
            log.debug(self.file_list)
            for f in self.file_list:
                log.debug("%s - %s - %s" % (repr(type(f)), repr(f), repr(os.path.isdir(f))))
                if os.path.isdir(f):
                    self.file_list.pop(self.file_list.index(f))
        except Exception as e:
            raise Exception(e.message)

    def exclude_files(self):
        for x in SETTINGS["excluded_files"]:
            for f in self.file_list:
                if f.endswith(x):
                    self.file_list.pop(self.file_list.index(f))

    def filtered_list(self):
        if not len(self.file_list):
            raise Exception("There is no file found.")
        log.info("{count} file{s} found".format(count=len(self.file_list),
                                                s='s' if len(self.file_list) > 1 else ''))
        return self.file_list

所以我的朋友们,你对此有何看法?

1 个答案:

答案 0 :(得分:1)

您可以修改在此部分代码中迭代的列表:

for f in self.file_list:
    log.debug("%s - %s - %s" % (repr(type(f)), repr(f), repr(os.path.isdir(f))))
    if os.path.isdir(f):
         self.file_list.pop(self.file_list.index(f))

迭代时更改self.file_list会中断for循环。 您可以像这样循环列表的副本:

for f in self.file_list[:]:

或者您必须将更改移出循环。