You need to open the file contents first and then perform a read by checking if the word you want is inside the file.
How to Open Python File ?
To open a Python file use the function open()
.
In this function you must pass the file path (only the name is required if the file is in the same directory as your program ) and the opening mode.
How to read Python files ?
After opening the file you will need to read the contents. For this there are three methods that you can use: read()
, readline()
and readlines()
.
In your case, I recommend using the read()
to speed things up.
Closing the file.
After opening and reading the file, you should close it using the method close()
. After using this method, you will no longer be able to access the contents of this file until it is opened again.
What would my code look like after all this ?
import glob
import os
key = "<Digite a palavra aqui>"
os.chdir('G:\PASTA\SUBPASTA')
for filename in glob.glob('*.asp'):
print("Verificando o arquivo",filename,"...")
file = open(filename)
if key in file.read():
print("A palavra",key,"existe no arquivo",filename+"!")
file.close()
I recommend that you study more about the open()
, because there are many more things in it that can be useful to you.
Can read the contents of a file?
– Woss
Not yet Anderson.
– LePy
So start by researching the function
open
and the libraryio
python native.– Woss
import glob import os Arq = os.chdir('G: PANALYTICS_PROD Iamdata-u Pesquant_c Sitessg Background') for file in glob.glob('*. Asp'): for info in open(file): #if info.read(). contain a_word('Bench'): #print(file)
– LePy
Anderson, I believe this is the way. I couldn’t evolve the issue of identifying the word inside the file
– LePy
if 'bench' in info.read()
would already solve, but let you study the library better to analyze the solution. Good luck.– Woss
Thank you Anderson. I will create the solution.
– LePy