首页 > 解决方案 > Python遍历文件,搜索特定字符串,如果找到,则复制其余行并合并到组合文件中

问题描述

我有一个包含 500 个文本文件的文件夹。Python 遍历文件搜索特定字符串,如果找到副本并合并为“Output.txt”的组合文件。我们在目录中的每个文件中查找的字符串

import os

searchquery = 'No' #string we are looking for in each of the file in the directory
def my_function(fname):
    Output=[]
    with fname as f1:
      with Output as f2:

        Lines = f1.readlines()

        try:
          i = Lines.index(searchquery)
          for iline in range(i+1, i+18): # we need to copy rest of the 18 or less line after 'No' is found
            f2.write(Lines[iline])
        except:
          print(" ")
    return Output

for filename in os.listdir('C:\\Users\\XXX\\Desktop\\Tox\\tcm2'):
    M1=open(filename)
    M2=my_function(M1)
    opened_file = open(Output.txt, 'a')
    opened_file.write("%r\n" % M1)
    opened_file.close()

我看到以下错误

    with Output as f2:
AttributeError: __enter__

标签: python

解决方案


你不能这样做with Output as f2,因为Output它是一个列表并且它不支持它,并且给你AttributeError: __enter__,另一个问题是你f2.write()再次执行的行你不能写入列表,append()而是使用。

这是完整的工作代码,我对其进行了测试:

import os
searchquery = 'No'
path = 'C:\\Users\\XXX\\Desktop\\Tox\\tcm2\\'

def my_function(fname):
    Output=[]           
    Lines = fname.readlines()   
    found = False 
    for line in Lines :
        if (found == True):
            Output.append(line)
        if line.startswith(searchquery):
            found = True
    return Output

opened_file = open('Output.txt', 'a')
for filename in os.listdir(path):
    M1=open(path+filename)
    result=my_function(M1)        
    for e in result:
        opened_file.write(e)        
    M1.close()
opened_file.close()

推荐阅读