Reputation: 22889
I'm writing a python script that will be aliased and run from various directories like this:
# working
python myScript.py file.txt
or:
# not working
python script/myScript.py other_file.txt
I'm referencing the file input like this:
file = sys.argv[1]
How can I have the script look for the file based on the command line users location instead of relative to the script's location?
Upvotes: 0
Views: 89
Reputation: 701
Try this:
import os
print(os.getcwd())
This will give you the current working directory(cwd). And using other functions like os.path.join
, you can achieve what you want.
Full example:
import os
import sys
def main():
if len(sys.argv) < 2:
print('Not enough arguments.')
sys.exit(1)
print('Current working directory: %s' % os.getcwd())
print('What you want: %s' % os.path.join(os.getcwd(), sys.argv[1]))
if __name__ == '__main__':
main()
Try using it.
Upvotes: 2