我正在尝试在目录内的所有文件中查找字符串 userType。
此代码适用于大多数文件,但我有一个文件 .DS_STORE 似乎与其他文件的编码方式不同。我知道我要找的字符串不在这个文件中,但它会破坏程序。如何跳过任何无法读取的文件?
这是我的代码:
import os
path = "/home/me/Work/myprojectvirtualenv/myproject/homepage/templates/"
direct = os.listdir(path)
for item in direct:
print("Checking " + item)
if 'userType' in open(os.path.join(path ,item)).read():
print("FOUND USERTYPE IN " + item)
请您参考如下方法:
只需根据您知道应该为您正在执行的特定操作引发的异常 使用try/except。我很确定您最有可能遇到的异常是 UnicodeDecodeError。或者,您也可以使用“read-bytes”打开文件 -> rb:
f = open('filename', 'rb')
更直接地解决您使用 try/except 的问题:
for item in direct:
print("Checking " + item)
try:
if 'userType' in open(os.path.join(path ,item)).read():
print("FOUND USERTYPE IN " + item)
except WhateverTheExceptionIsYouWantToCatch:
pass
执行上述操作会在发生意外情况时引发,这样您就可以确定要如何继续,否则继续。
作为额外的奖励,我还建议在打开时显式调用 .close,或者更好并强烈建议使用上下文为您处理打开/关闭,这样您不要以一堆打开的文件结束。
for item in direct:
print("Checking " + item)
try:
with open(os.path.join(path, item)) as f:
if 'userType' in f.read():
print("FOUND USERTYPE IN " + item)
except WhateverTheExceptionIsYouWantToCatch:
pass
最后,到了this的地步评论,您可能应该确保您甚至想要打开您可能不关心的某些文件。按照相应答案中的建议使用 glob ,您可能会过滤到您真正关心的文件。
使用pathlib
这也是开始使用 pathlib 的好机会,因为它提供了很棒的工具。
