python 2.7操作系统路径.isdir(unicode abspath字符串)不返回任何内容

2024-05-15 00:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在os.listdir输出中查找文件夹。但是,os.path.isdir没有返回self.file_list中名为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']

列表中的最后一件事几天来一直让人头疼。在

^{pr2}$

到目前为止,一切正常,但当我把它放在我的项目,它开始失败。当我调用GetFileList().filtered_list()时,运行exclude_directories()方法时,没有对文件夹u'\u0130letildi'的跟踪。但是,在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'目录在list log中可用。但是当列表在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

朋友们,你们对此有何看法?在


Tags: pathinselflogtargetosdefdir
1条回答
网友
1楼 · 发布于 2024-05-15 00:53:45

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

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_列表迭代时,它会中断for循环。 您可以这样循环列表的副本:

^{pr2}$

或者你必须把改变移出循环。在

相关问题 更多 >

    热门问题