Python Forum

Full Version: How to print current pwd?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Assume I want to print out the current pwd from inside a python v3 script.

The following does not work:

import os
print("pwd=" + os.getcwd())


How else can I achieve this?

Peter
Why do you need another method?
What do you mean with "another method"?

Which method would be better?
Your code works. What is your problem?
You can use string formating.

import os

print("pwd=%s" % os.getcwd()) # old style formating
print("pwd={}".format(os.getcwd())) # currently used string formating
print(f"pwd={os.getcwd()}") # format string since Python 3.6
Output:
pwd=/home/andre pwd=/home/andre pwd=/home/andre
If want a different way can use pathlib.
Work the same,but it detect OS path WindowsPath and PosixPath.
If print() the OS path dos not show.

Windows:
C:\
λ cd 1
C:\1
λ ptpython
>>> import os
>>> os.getcwd()
'C:\\1'

>>> from pathlib import Path
>>> Path.cwd()
WindowsPath('C:/1')
>>> print(f'pwd={Path.cwd()}')
pwd=C:\1
Linux:
mint@mint ~/.pyenv $ ptpython3
>>> import os
>>> os.getcwd()
'/home/mint/.pyenv'

>>> from pathlib import Path
>>> Path.cwd()
PosixPath('/home/mint/.pyenv')
>>> print(f'pwd={Path.cwd()}')
pwd=/home/mint/.pyenv
import os 
dir_path = os.path.dirname(os.path.realpath(__file__))
regards,
Christian