1

What's wrong with the way I'm joining my path here?

Everything but the first item in the list will be properly joined.

I'm grabbing a path from a filedialog in tkinter.

i.e filedialog.askdirectory()

Example Path:

PATH = "C:/MyUserName/Desktop/SomeDir"

What I'm doing:

os.path.join(*(PATH.split("/") + ["somefile.txt"]))

This will print out the following:

C:MyUserName/Desktop/SomeDir/somefile.txt

Why does it lose the first /?

Pythonista
  • 11,377
  • 2
  • 31
  • 50

3 Answers3

3

I needed to convert my initial path using os.normpath I was getting a filedialog input from tkinter and then trying to use the above path style / code in the question to access / create files.

Because of the bad join / seperators on windows it was causing errors.

Pythonista
  • 11,377
  • 2
  • 31
  • 50
2

You are using Windows, right?

From the Docs:

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

This means that c:foo is in fact a correct path. Try os.path.abspath('c:foo') and os.path.abspath('c:\\foo') to see the difference. The first path is a relative path on the c drive and the second one is an absolute path.

Felix
  • 6,131
  • 4
  • 24
  • 44
2

Windows keeps a current path for all drives. C:MyUserName/Desktop/SomeDir/somefile.txt and C:/MyUserName/Desktop/SomeDir/somefile.txt are both valid and there is no way for ntpath.join to know whether you wanted the drive-relative or drive-absolute path.

tdelaney
  • 73,364
  • 6
  • 83
  • 116