I am converting a shell script into a Python script and having some trouble with testing an IF condition. In this environment we are running Python 3.9.2.
I originally set 2 variables (homeDir and curDir), create an if-else condition to test if the variables are equal.
Running the script I do a cd to the $HOME directory and run the Python script.
It always prints "False", even when the console output shows the variables are equal.
I am expecting the script to return "Take Action ABC" when running the script in the $HOME directory.
Screen capture showing the output:
Sample of the code:
import os
from pathlib import Path
homeDir = Path.home()
curDir = os.getcwd()
print('DEBUG homeDir:', homeDir)
print('DEBUG curDir:', curDir)
if curDir == homeDir:
print('True')
else:
print('False')
You have objects of different types; homeDir
is a Path
object, while curDir
is a str
. For that reason they won't compare equal, even if semantically they are the same path. Use one module or the other instead of mixing pathlib
and os
. One solution would be to replace
os.getcwd()
with
Path.cwd()
The latter is thepathlib
equivalent to os.getcwd()
.
Example from a Python 3.9 REPL invoked from where my current directory is my user home directory:
>>> os.getcwd() == Path.home()
False
>>> Path.cwd() == Path.home()
True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.