1

I very new to python. I am trying to find all python files that hav the string "DATASOURCE" inside them and to print the path name of the files. I'm using this code:

import os,glob

os.chdir(r"G:\PROJECTS\menofim_3_5\gis")
for file in glob.glob('*.py'):
    with open(file) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print file

I only get this result:

>>> 
findAndReplaceWorkspacePaths-dwg.py
Remove FGB by dataSource excluding specific mxd.py
SelectLayerByLocation2.py
SelectLayerByLocation3.py
>>>

I have succeeded in printing the file name, but I don't know how to print the path name of the files.

3
  • Is this wrong? Explain what did you expect. By the way, you don't close a file in your code when done with it. Commented Mar 28, 2017 at 12:29
  • @АндрейЧереваткин: You don't need to explicitly close the file when using with Commented Mar 29, 2017 at 7:06
  • Ah, right. Sorry. Commented Mar 29, 2017 at 10:50

1 Answer 1

1

Use os.path.join to connect the dirname to the filename:

import os, glob

dirname = r"G:\PROJECTS\menofim_3_5\gis"
os.chdir(dirname)
for filename in glob.glob('*.py'):
    with open(filename) as f:
        contents = f.read()
    if 'DATASOURCE' in contents:
        print os.path.join(dirname, filename)
        print file
Sign up to request clarification or add additional context in comments.

1 Comment

Raymond Hettinger, change the last line into "print filename"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.