[英]Ignoring specific files with `os.listdir`
How can I change this python code to ignore Mac OS' .DS_Store files? 如何更改此python代码以忽略Mac OS的.DS_Store文件?
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname):
for line in open(os.path.join(self.dirname, fname)):
yield line.split()
Edit: This question looks a lot like this question ( How to ignore hidden files using os.listdir()? ) but I don't know how to implement that solution into the above class. 编辑:这个问题看起来很像这个问题( 如何使用os.listdir()忽略隐藏的文件? ),但我不知道如何将解决方案实现到上面的类中。 I tried this:
我尝试了这个:
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname) if not fname.startswith('.'):
for line in open(os.path.join(self.dirname, fname)):
yield line.split()
But it didn't work. 但这没有用。
You can use an if-statement here by checking that the file name is not equal ( !=
) to "DS_Store": 您可以在此处使用if语句,方法是检查文件名不等于(
!=
)与“ DS_Store”:
class MySentences(object):
def __init__(self, dirname):
self.dirname = dirname
def __iter__(self):
for fname in os.listdir(self.dirname):
if fname != '.DS_Store':
for line in open(os.path.join(self.dirname, fname)):
yield line.split()
If the filename does equal this string, then that loop is simply passed-over without the nested for
statement being touched. 如果文件名确实等于该字符串,那么将直接传递该循环,而不会触及嵌套的
for
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.