Friday, March 21, 2014

File Location of Running Python Script

Problem : During development phase I was saving files with file.open("filename"), for this the python interpretor tries and search the file in the directory where the script is located.  For the development part this was good but once deployed to production and where  corntab script was suppose to execute it , the interpretor was not looking for these files in the directory of the script resulting in code break.

Solution: Instead of absolute file names or path provide path relative to the script or python file that is running


  1. Get Path of the directory where current python script is running
  2. import os
  3. filepath  = os.path.dirname(os.path.realpath(__file__)) + "/"+"filename"
  4. Now the file path will have the file you want to open
  5. file = open(filepath)
And with this we are good to go !


No comments:

Post a Comment