1

I have a program that I wrote that goes through all of the files in a directory and looks for files with a flag and then inputs them into a different program. It works great, the only thing that I am trying to do now it put the script in one location on a box, and then have it know to look in the directory that I am currently in as the working directory. Currently all I do is mv the script into whatever directory I am working in and just call it from there, but that is tedious and requires me to constantly be cp'ing the script.

I am just hoping there is a little more elegant way to do this? Any help would be appreciated.

Michael R
  • 259
  • 5
  • 16

4 Answers4

7

what about

import os

loc = os.getcwd()
greole
  • 4,523
  • 5
  • 29
  • 49
1

The __file__ object can return such information:

import os

os.path.dirname(__file__)
skeryl
  • 5,225
  • 4
  • 26
  • 28
  • 1
    This will give you the directory that the current *file* is in which may not be your current directory. – Steve Barnes Jan 13 '14 at 22:07
  • Right, I misread the original question. Also, as a result, this must be called form __within__ a file to work correctly. – skeryl Jan 13 '14 at 22:26
0

If you are comfortable passing the working directory as an argument to the script, the following approach will work.

#!/usr/bin/env python
import sys
import os

workingDir = sys.argv[1]
os.chdir (workingDir)

# Your code here
Spade
  • 2,220
  • 1
  • 19
  • 29
0

Sounds like a perfect use for os.walk() the example from the help would be a good starting point:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73