Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonを使用してファイルが存在するかどうかを確認するにはどうすればよいですか?


os.access(path、mode)を使用して、ファイルのアクセス許可と、読み取り、書き込み、実行のアクセス許可のモードでの存在を確認できます。

>>> import os
>>> os.access('my_file', os.F_OK) # Check for existence of file
True
>>> os.access('my_file', os.R_OK) # Check for read access
True
>>> os.access('my_file', os.W_OK) # Check for write access
True
>>> os.access('my_file', os.X_OK) # Check for execution access
False

  1. Pythonを使用してファイルを削除するにはどうすればよいですか?

    osモジュールの関数を含む単一のファイルまたは単一の空のフォルダーを削除できます。たとえば、ファイルmy_file.txtを削除する場合は、 >>> import os >>> os.remove('my_file.txt') os.removeの引数は、絶対パスまたは相対パスである必要があります。

  2. Python変数が存在するかどうかを確認するにはどうすればよいですか?

    次のコードを使用して、Pythonに変数が存在するかどうかを確認します。 例 x =10 class foo: g = 'rt' def bar(self): m=6 print (locals()) if 'm' in locals(): print ('m is local variable') else: print ('m is not a local variable') f = foo() f.bar() print (globals()) if hasattr(f, 'g'): print ('