3

I'm new to Python, and currently using the os module. I came across a doubt.

Can anyone explain me, what is the difference between the following lines?

os.mkdir('dir_name')
os.mkdir('/dir_name')

The former creates the folder in the current directory but what about the later? There's no folder created in the current directory, where is it created then?

Simon Hessner
  • 1,757
  • 1
  • 22
  • 49
Nerd001
  • 151
  • 1
  • 1
  • 8
  • 8
    The first is a _relative_, the second an _absolute_ path. A relative path is interpreted relative to the current working directory your process is in, an absolute path is interpreted from the systems file system root node (`/`). – arkascha Sep 17 '18 at 13:54
  • 2
    The 2nd is an *absolute* path and will be created in the *FS* root ("*/*", or directly on the drive returned as part of by `os.getcwd()`). – CristiFati Sep 17 '18 at 13:56
  • 2
    The second creates the folder in the root directory ('/'). This usually requires root privileges. – Simon Hessner Sep 17 '18 at 13:58

2 Answers2

2
os.mkdir('dir_name')  # relative

The first path is relative. The first code line will make a directory "dir_name" in the current working directory. It is relative because the path will change relative to the working directory.

os.mkdir('/dir_name')  # absolute

This second path is absolute. "/" refers the the operating system's root directory. The second code snippet will make a "dir_name" directory in the root directory. The path is absolute because unlike the "current working directory", the root directory will never change.

Christopher Nuccio
  • 596
  • 1
  • 9
  • 21
1

Consider os.mkdir('../dir_name') for full picture. It is also a relative, but uses .. to denote upper level folder, relative to current one.

Evgeny
  • 4,173
  • 2
  • 19
  • 39