Usage instructions of os module os. path. exists of in python

  • 2021-10-11 18:56:12
  • OfStack

os is operating system (operating system), and the os module of Python encapsulates common file and directory operations.

os. path module is mainly used to obtain the attributes of files, and exists means "existence", so as the name implies, os. path. exists () means to judge whether the files in brackets exist, and the files in brackets can be file paths.

Take chestnuts:

user. py is a file that exists in the current directory

Enter code:


import os
path = os.path.exists('user.py')
print(path)

Output:


True
 
Process finished with exit code 0

If it does not exist, FALSE is returned.

Additional:

Application of os. path and os. makedirs in Python

Determine whether a file or folder exists and create a folder


import os
import numpy as np
 
data = np.array([1, 2, 3])
if not os.path.exists("./data/"):
 print("# path not exists")
 os.makedirs("./data/")
 if not os.path.exists("./data/data.npy"):
  print("# data.npy not exists")
  np.save("./data/data.npy", data)
 
print("# path exists? :", os.path.exists("./data/"))
print("# data.npy exists? :", os.path.exists("./data/data.npy"))

Run results:


# path not exists
# data.npy not exists
# path exists? : True
# data.npy exists? : True

Related articles: