パスが存在しない場合はディレクトリを作成しようとしていますが、! (not) 演算子は機能しません。Pythonで否定する方法がわかりません...これを行う正しい方法は何ですか?
if (!os.path.exists("/usr/share/sounds/blues")):
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
Pythonの否定演算子はですnot
。!
したがって、をに置き換えてくださいnot
。
あなたの例では、これを行います:
if not os.path.exists("/usr/share/sounds/blues") :
proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
proc.wait()
特定の例(ニールがコメントで述べたように)では、subprocess
モジュールを使用する必要はありませんos.mkdir()
。例外処理の優れた機能を追加して、必要な結果を取得するために使用できます。
例:
blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
try:
os.mkdir(blues_sounds_path)
except OSError:
# Handle the case where the directory could not be created.
Pythonは、句読点よりも英語のキーワードを好みます。を使用not x
しnot os.path.exists(...)
ます。同じことがPythonにも当てはまり&&
ます。||
and
or
代わりに試してください:
if not os.path.exists(pathName):
do this
他のすべての人からの入力を組み合わせると (使用しない、かっこを使用しない、使用するos.mkdir
)...
special_path_for_john = "/usr/share/sounds/blues"
if not os.path.exists(special_path_for_john):
os.mkdir(special_path_for_john)