打开未知文件时出错

2024-05-20 17:10:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在上面的代码中,这是一个文件搜索脚本,包含2个文件; 首先是搜索应用程序.py它是一个类,包含一些方法来获取目的地,并在其中搜索文本。 其次,主.py,这是我导入的文件搜索应用程序.py我在那里使用了它的方法。
当我尝试在包含脚本的目录中搜索文本时,它工作正常,但每当我尝试在其他目录中搜索时,就会发生不好的事情,并引发编码错误,FileNotFound和。。。 这里是搜索应用程序.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)

这就是主.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)

Tags: pathtextinpyselftargetforsearch
2条回答

我认为试一试是个好办法。我会把它放在for line in f块周围。如果文件的utf-8失败,可以使用open(file,'r', encoding='latin-1')重试。这不会引起如here所述的错误,但是如果实际编码与拉丁语-1不同,那么检索到的内容可能是无用的。你知道吗

您还可以检查文件扩展名并跳过某些二进制文件,如.jpg、.exe、。。。你知道吗

对于FileNotFound错误,您应该在打开文件之前用os.path.isfile()检查文件是否存在。您还可以在open()周围放置try/except,因为可能存在无法打开的文件(权限错误、文件突然被删除等)

Question: search in other directories bad things happen and it raise encoding error, FileNotFound

很可能您试图打开一个目录
os.path.isfile(...)测试并只处理那些文件。你知道吗

正如@venify所指出的,您还应该只打开和阅读文本文件*
一种简单的方法是文件扩展名,例如.txt
但请记住,情况并非总是如此。你知道吗

例如:

import os

root = "../test"
# Loop the os.listdir entrys
for entry in os.listdir(root):
    # Create a relative Path
    fpath = os.path.join(root, entry)

    # Test if it's a regular file
    if os.path.isfile(fpath):

        # Get the Filename Extension
        ext = os.path.splitext(entry)
        print("\t{} ext:{}".format(entry, os.path.splitext(entry)))

        # Test if Extension is in your List of Extensions
        if ext[1] in ['.txt', '.py']:
            print("\t\tProcess {}".format(fpath))
        else:
            print("Skipt '{}', file extension not in list!".format(entry))

    else:
        print("Skip '{}', is not a file!".format(entry))

Output:

    test.lnk ext:('test', '.lnk')  
Skipt 'test.lnk', file extension not in list!  
    atom.xml ext:('atom', '.xml')  
Skipt 'atom.xml', file extension not in list!  
    power.txt ext:('power', '.txt')  
        Process ../test/power.txt  
Skip 'tar', is not a file!  
    test ext:('test', '')  
Skipt 'test', file extension not in list!  
    test.xlsx ext:('test', '.xlsx')  
Skipt 'test.xlsx', file extension not in list!  

用Python:3.4.2测试

相关问题 更多 >