Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python3查找字符串_Python - Fatal编程技术网

使用Python3查找字符串

使用Python3查找字符串,python,Python,这是我目前的代码: import os class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' user_input = input('What

这是我目前的代码:

import os

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


user_input = input('What is the name of your directory')
directory = os.listdir(user_input)

searchstring = "import os"

for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        # Full path
        f = open(user_input + os.sep + fname, 'r')
        if searchstring in f.read():
            print(bcolors.OKGREEN + '[-]' + bcolors.ENDC + 'String found in file' % fname )
        else:
            print(bcolors.FAIL + '[+]' + bcolors.ENDC + 'String not found in file  %s' %fname)
        f.close()
我正在试图看到错误…我不确定。我的目标是找到一个字符串。 为什么我会得到这个:

Traceback (most recent call last):
  File "/Users/jl/Downloads/Simple-Adware-master/src/adware/findstring.py", line 23, in <module>
    if searchstring in f.read():
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte
回溯(最近一次呼叫最后一次):
文件“/Users/jl/Downloads/Simple Adware master/src/Adware/findstring.py”,第23行,在
如果在f.read()中搜索字符串:
文件“/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py”,第322行,在decode中
(结果,消耗)=自身缓冲区解码(数据,自身错误,最终)
UnicodeDecodeError:“utf-8”编解码器无法解码位置3131中的字节0x80:无效的开始字节
我不知道如何以及为什么会出现这个错误。 有什么想法吗?非常感谢。
没关系,这个问题解决了:) 这是新代码

#Import os module
import os
from time import sleep

#The colours of the things
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

# Ask the user to enter string to search
search_path = input("Enter directory path to search : ")
file_type = input("File Type : ")
search_str = input("Enter the search string : ")

# Append a directory separator if not already present
if not (search_path.endswith("/") or search_path.endswith("\\") ): 
        search_path = search_path + "/"
                                                          
# If path does not exist, set search path to current directory
if not os.path.exists(search_path):
        search_path ="."

# Repeat for each file in the directory  
for fname in os.listdir(path=search_path):

   # Apply file type filter   
   if fname.endswith(file_type):

        # Open file for reading
        fo = open(search_path + fname, 'r')

        # Read the first line from the file
        line = fo.read()

        # Initialize counter for line number
        line_no = 1

        # Loop until EOF
        if line != '' :
                # Search for string in line
                index = line.find(search_str)
                if ( index != -1) :
                    print(bcolors.OKGREEN + '[+]' + bcolors.ENDC + ' ', fname, sep="")
                    print('      ')
                    sleep(0.01)
                else:
                    print(bcolors.FAIL + '[-]' + bcolors.ENDC + ' ',  fname, ' ', 'does not contain', ' ', search_str, sep="")
                    print("       ")
                    sleep(0.01)
                line = fo.readline()  

                # Increment line counter
                line_no += 1
        # Close the files
        fo.close()
    

现在问题解决了。

可能找到了一个二进制文件。您可以尝试另一种方法-以二进制形式打开文件(使用
'rb'
而不是
'r'
),然后尝试在字节内找到编码的搜索字符串(
如果f.read()中的searchstring.encode():
)-与其尝试解码文件中的字节,不如尝试在不使用输入的情况下写入路径会发生什么,如果再次出现Unicode错误,您可以尝试r'your_path'。@jairoh这不是问题所在。问题是,它已作为文本文件使用
'r'
打开,因此
read
尝试返回字符串,因此它尝试将字节解码为utf-8,但失败。我猜它在目录中找到了一个二进制文件。打印文件名是调试的第一步。请不要在问题中添加[已解决]。答案左侧有一个绿色的勾号箭头,您可以使用它将问题标记为已解决