How do i change the working dir to programs dir

this is my code:

import time
import subprocess
import os
from pathlib import Path

os.chdir()

m = input("do you want to open an image: ")

if m == "y" and "Y":
    os.startfile("image1.jpg")

but i dont know what to put on os.chdir() to change working directory to where it is.

so if it is on documents it would work (if image1 is in the documents) if it is in desktop it would work (if image1 is in the desktop)

__file__ holds the path lf the script and os.path.dirname(...) will return the directory part of a filepath.

Additional: m == "y" and "Y" is equivalent to (m == "y") and "Y". What you want is m in {"y", "Y"}, or, better yet, m.lower() == "y".

2 Likes

If you are looking to just open a particular file, there is no need to change the current working directory. You can simply provide its directory location. Say, for example that your file is located on the Desktop. We assign a variable with its path. If we then provide the name of the file that we are interested in opening, we append the file name to this directory.

import subprocess
from pathlib import Path

# Directory where your files are kept
directory = 'C:\\Desktop\\'

def open_file(file):

    file_path = Path(directory + file)
    subprocess.Popen(fr'explorer "{file_path}"')

# Provide filename here
file = 'file_name_here.jpg'
open_file(file)

You can modify this script to suit your particular preferences. For example, you can also pass in an argument that includes the entire path (directory and filename) to the open_file function versus a fixed directory and an independent filename.

If you want the Desktop directory, that’s os.path.join(os.path.expanduser("~"), "Desktop").

I agree that there’s no need to change the current working directory. It’s better to work with the full filepaths instead.

import os

filename=’/home/a/image.jpg'

dir = os.path.dirname(filename)

os.chdir(dir)

Just to correct the syntax, so no errors will be raised for people trying this. I suppose you meant filename='/home/a/image.jpg'?

[/quote]

Did you already fix it for me?
Thank you, I appreciate it.

My point was that os .path.dirname(filename) returns the directory without the file name