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, 2020 in Python by kartik
• 37,520 points
774 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, 2020 by Niroj
• 82,840 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
28,836 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,720 points
2,340 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,720 points
2,310 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 29, 2020 in Python by The real slim shady
4,721 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
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, 2020 in Python by Niroj
• 82,840 points
762 views
0 votes
1 answer

How can I open multiple files using “with open” in Python?

Hello, Just replace and with , and you're done: try: ...READ MORE

answered Nov 20, 2020 in Python by Niroj
• 82,840 points
1,519 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP