试图遍历目录中的文本文件,打开每个文本文件,搜索内容,并在找到匹配项时打印

问题描述 投票:0回答:1

我的代码必须关闭,但是这里有问题。我试图遍历目录中的文本文件,打开每个文本文件,搜索内容,并在字符串中找到匹配项时进行打印。

import os

search_path = 'C:\\my_path\\'
file_type = '.txt'
search_str = ['941','266','881']

search_str = str(search_str)
my_list = search_str.split(",")
for i in my_list:
    #print(i)
    # 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)

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

            # Initialize counter for line number
            line_no = 1

            # Loop until EOF
            while line != '':
                # Search for string in line
                index = line.find(my_list)
                if (index != -1):
                    print(fname, "[", line_no, ",", index, "] ", line, sep="")

                # Read next line
                line = fo.readline()

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

[当我运行它时,出现错误说明:TypeError: must be str, not list

search_str = str(search_str)
my_list = search_str.split(",")

我将列表转换为字符串并拆分字符串。不知道问题出在哪里。如果有人可以看到它,请告诉我。谢谢。

python python-3.x
1个回答
0
投票

您的search_str已经是列表。您无需将其转换为字符串,然后将其拆分为列表。当您执行此操作时,my_list的三个元素将变为“ ['941'”,“'266'”和“'881']”

© www.soinside.com 2019 - 2024. All rights reserved.