s9dw
s9dw

Reputation: 31

python change default directory

so I recently tried using playsound and the .mp3 is in the same folder as the .py, and it says it could not find the file.

I printed out the current directory and it says it's at C:\Users\me

Shouldn't this be at the same directory as where the .py script is at? This has been happening with my other python scripts where I have to explicitly give it the directory, whereas before I didn't have to and it was just where the python script was at.

Is there a setting for this?

Upvotes: 0

Views: 673

Answers (2)

Frank Yellin
Frank Yellin

Reputation: 11285

If you're looking for a file in the same directory as the executing python program:

basename = os.path.basename(__file__)
my_file_name = basename + "/myfile"
with open(my_file_name) as my_file:
   ...

The variable __file__ contains the full pathname of the currently executing Python program.

Upvotes: 0

Pedro Maia
Pedro Maia

Reputation: 2722

The current directory is defined by where you execute the python file not the location of it. If you want to change the directory you can use the os module:

import os
os.chdir(PATH)

Upvotes: 1

Related Questions