python 2.7 os.path.isdir(unicode 绝对路径字符串) returns 无
python 2.7 os.path.isdir(unicode abspath string) returns nothing
我正在尝试在 os.listdir
输出中查找文件夹。但是,os.path.isdir
returns 在 self.file_list
中的那个名为 u'\u0130letildi'
的目录与该列表中的 unicode 目录无关。所以我无法从 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循环中遍历list就没有trace了
这是我的 类:
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
那么小伙伴们,你们对此有什么看法呢?
您修改您在这部分代码中迭代的列表:
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[:]:
或者您必须将更改移出循环。
我正在尝试在 os.listdir
输出中查找文件夹。但是,os.path.isdir
returns 在 self.file_list
中的那个名为 u'\u0130letildi'
的目录与该列表中的 unicode 目录无关。所以我无法从 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循环中遍历list就没有trace了
这是我的 类:
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
那么小伙伴们,你们对此有什么看法呢?
您修改您在这部分代码中迭代的列表:
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[:]:
或者您必须将更改移出循环。