How can I find script's directory with Python?

0 votes

Hii,

Consider the following Python code:

import os
print os.getcwd()

I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints .

How can I get the path to the script from within a script run by a Django view?

May 11 in Python by kartik
• 27,140 points
75 views

1 answer to this question.

0 votes

Hii,

You need to call os.path.realpath on __file__, so that when __file__ is a filename without the path you still get the dir path:

import os
print(os.path.dirname(os.path.realpath(__file__)))

Thank you!!

answered May 11 by Niroj
• 58,500 points

Related Questions In Python

+2 votes
6 answers

How can I change directory or "cd" in Python?

Context Manager: cd import os class cd:     """Context manager for ...READ MORE

answered Oct 18, 2018 in Python by Nabarupa
3,880 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,780 points
309 views
0 votes
1 answer

How can I logarithmic axes with matplotlib in python?

You can use the Axes.set_yscale method. That allows you ...READ MORE

answered Oct 15, 2018 in Python by charlie_brown
• 7,780 points
1,217 views
0 votes
2 answers

How can I rename multiple files in a certain directory using Python?

import os from optparse import OptionParser, Option class MyOption ...READ MORE

answered Jul 28 in Python by The real slim shady
2,100 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,355 views
0 votes
0 answers
0 votes
1 answer

How Can I log a Python error with debug information?

Hii, Using exc_info options may be better, to allow you ...READ MORE

answered May 27 in Python by Niroj
• 58,500 points
193 views
0 votes
1 answer

How do I log a Python error with debug information?

Hii, In most applications, you won't be calling ...READ MORE

answered May 11 in Python by Niroj
• 58,500 points
75 views