我正在尝试在os.listdir
输出中查找文件夹。但是,当面对列表中的unicode目录时,os.path.isdir
不返回关于self.file_list
中名为u'u0130letildi'
的目录的任何信息。所以我不能从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()
时,在运行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'
目录在列表日志中可用。但是,当列表在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
朋友们,你们对此有什么看法?
您可以修改在代码的这一部分中迭代的列表:
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[:]:
或者您必须将更改移出循环。