python - 打开未知文件的错误
问题描述
在上面的代码中,这是一个文件搜索脚本,包含 2 个文件;首先,SearchApp.py 是一个类,它有一些获取目的地的方法和在那里搜索它的文本。其次, Main.py ,这是我导入 SearchApp.py 的文件,我在那里使用了它的方法。
当我尝试在包含脚本的目录中搜索文本时,它工作正常,但每当我尝试在其他目录中搜索时,就会发生坏事并引发编码错误,FileNotFound 和......这是 SearchApp.py:
import os
class Searcher(object):
"""Search class for our app :D """
def __init__(self):
self.items = []
self.matches = []
def header():
print("TATI Search App".center(75,'-'))
def get_destinition(self):
path = input("Where should I search? ")
if not path or not path.strip():
return None
if not os.path.isdir(path):
return None
return os.path.abspath(path)
def get_text(self):
text = input('enter text to search: ')
return text
def search_dir(self, directory, text):
self.directory = directory
self.text = text
items_in_dir = os.listdir(directory)
for item in items_in_dir:
if not os.path.isdir(os.path.join(directory,item)):
self.items.append(os.path.join(directory,item))
def search_text(self,target):
self.target = target
for file in self.items:
with open (file,'r',encoding='utf-8')as f:
for line in f:
if line.find(target) >0:
self.matches.append(line)
for found_item in self.matches:
print(found_item)
这是 Main.py:
from searchApp import Searcher
searcher = Searcher()
path = searcher.get_destinition()
target = searcher.get_text()
directories = searcher.search_dir(path,target)
searcher.search_text(target)
解决方案
我认为 try/except 是一个很好的解决方案。我会把它放在for line in f
街区周围。如果文件的 utf-8 失败,您可以使用open(file,'r', encoding='latin-1')
. 这不会引发此处描述的错误,但如果实际编码与 latin-1 不同,则检索到的内容可能无用。
您还可以检查文件扩展名并跳过某些二进制文件,如 .jpg、.exe、...
对于FileNotFound错误,您应该在打开文件之前使用os.path.isfile()检查文件是否存在。您也可以在周围放置一个 try/except ,open()
因为可能存在无法打开的文件(权限错误、文件突然删除等)
推荐阅读
- reactjs - 将 react-day-picker 范围限制为 x 天
- java - Java 到 Slack API:SlackError{type=MISSING_SCOPE, error=missing_scope}
- typescript - Typescript - 如何从哈希图中删除值?
- dictionary - python嵌套字典中的棘手行为
- php - 如何在 wordpress 中删除数据库中的主表而不丢失 wordpress 站点?
- c# - c# .Net Visual Studio 显示导致页面显示的执行路径
- python - TypeError:“int”和“list”的实例之间不支持“>”
- css - 如何调整mat-option的位置
- c# - 复杂对象的隐藏字段未传递给控制器
- string - PowerShell 匹配字符串中的模式