python - 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__
解决方案
你不能这样做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()
推荐阅读
- c# - 带有 SQL Server LocalDB 的 Winform 应用程序变得无响应
- reactjs - 在 Google Kubernetes Engine 中出现 crashloopbackoff 错误
- php - 在 sendgrid 上的 setFrom 上遇到错误,在 sendgrid 中找不到 wrd
- python-3.x - 如何在控制台中打印字符串并编辑它?
- database - 如何从段名中查找 Oracle 数据库对象名?
- amazon-web-services - 如何在 AWS EC2 实例之间发送和接收数据?
- python - 映射和切片列值
- ruby-on-rails - Rails 中的 facebook 如何无限滚动?
- java - 带有 JDBC SQLite 的 DriverManager.getConnection() 在某些 PC 上挂起
- twilio - 无法修改正在进行的通话