2

I have a parent folder named A, which contains my Python script. The script creates a sub folder, also within A.

I'm unsure how I should reference the path when creating the new sub folder because:

  1. I can't use absolute path because each user will have their username as part of the path to the Git repo.

  2. I'm worried about using relative path because I don't know from which folder users will execute the script.

How is this typically handled?

intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • 2
    Tell your users to run the script from a specific directory so they don't do it wrong. Or write some code that navigates backwards until it finds your directory (not sure if that would meet your requirements though) – byxor Jan 14 '22 at 16:50
  • 2
    You can construct an absolute path given a user name. Can you provide more details about how `A` and the user's name will be used? – chepner Jan 14 '22 at 16:52

1 Answers1

1

use __file__ to get the path to the python script you are in, regardless of where the script is run from.

from pathlib import Path
script_path_dir = Path(__file__).parent
sub_folder = script_path_dir / 'your_subfolder'
hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51