Reputation: 314
I am developing a script which will find particular key or string from the file path containing in text file. I have tried to run below code but I am getting error.
import glob
print 'Named explicitly:'
for name in glob.glob('/apps/mongodba/*.conf'):
with open('out.txt', 'a') as f:
print >> f, name
with open("lst.txt", "w") as f:
with open('out.txt') as currentFile:
text = open(currentFile, "r")
for line in text:
if "26012" in line:
f.write('string found')
else:
f.write('string not found')
Error:
Traceback (most recent call last):
File "find_y.py", line 11, in <module>
text = open(currentFile, "r")
TypeError: coercing to Unicode: need string or buffer, file found
cat out.txt:
>cat out.txt
/apps/mongodba/mongo.conf
/apps/mongodba/mongo_clust.conf
Desired output:
String found on file /apps/mongodba/mongo.conf
Upvotes: 0
Views: 77
Reputation: 13
Not sure what actually you wanted to do but I see a bug in your code.
text = open(currentFile, "r")
The above line is not correct.
When you open()
as
currentFile
. Here currentFile
is an object not a string or byte.
Here is a fixed code.
with open("lst.txt", "w") as f:
with open('out.txt') as currentFile:
text = currentFile.readlines()
for line in text:
if "26012" in line:
f.write('string found')
else:
f.write('string not found')
Edit: If you are not processing too many lines. Then you can do something like this. It is not the best way but a quick solution.
things_to_write = []
with open('out.txt', r) as f:
file_paths = f.readlines()
for file_path in file_paths:
with open(file_path.strip('\n') as a:
text = a.read()
if "26012" in text:
string = 'Found' + file_path
else:
string = 'Not Found' + file_path
thing_to_write.append(string)
with open('lst.txt', 'w') as wr:
wr.writelines(things_to_write)
Upvotes: 1