Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print current pwd?
#1
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
Reply
#2
Why do you need another method?
Reply
#3
What do you mean with "another method"?

Which method would be better?
Reply
#4
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
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
Reply
#6
import os 
dir_path = os.path.dirname(os.path.realpath(__file__))
regards,
Christian
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to print the current time in color julio2000 3 2,736 Apr-16-2020, 10:21 AM
Last Post: julio2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020