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
• 11,890 points
20 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
• 23,950 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
1,339 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,760 points
242 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,760 points
1,075 views
0 votes
1 answer

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

Use os.rename(src, dst) to rename or move a file ...READ MORE

answered Nov 23, 2018 in Python by aryya
• 7,350 points
1,307 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 963 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
• 23,950 points
132 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
• 23,950 points
26 views