1. 判断路径
os.path.exists
;
FilePath='path01/path02/path03'
def auto_create_path(FilePath):
if os.path.exists(FilePath): ##目录存在,返回为真
print( 'dir exists' )
else:
print( 'dir not exists')
os.makedirs(FilePath)
// os.mkdir(FilePath)
auto_create_path(FilePath)
os.mkdir()
创建路径中的最后一级目录,即:只创建path_03
目录,而如果之前的目录不存在并且也需要创建的话,就会报错。
os.makedirs()
创建多层目录,即:Test,path_01,path_02,path_03
如果都不存在的话,会自动创建,但是如果path_03
也就是最后一级目录.
import json
import os
result = ['test']
if not os.path.exists('/new/'):
os.mkdir('/new/')
with open('/new/test.json', 'w') as fp:
print('h')
json.dump(result, fp, indent = 4, separators = (',', ':') )
2. 判断文件是否存在
# importing os module
import os
# Specify path
path = '/usr/local/bin/'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
# Specify path
path = '/home/User/Desktop/file.txt'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
参考: