模块的导入与执行
vim test.py # 建立test.py
# test.py
def say_morning():
print('Good morning %s' % __name__)
if __name__ == '__main__':
say_morning()
chmod u+x test.py # 修改test.py为可执行文件
当使用python test.py
执行的时候输出Good morning __main__
,当在Python中导入时,如下
import test
test.say_morning()
# -> Good morning test
当执行的时候,执行了test.py中的if语句,当在Python中导入时,__name__自动复制为模块名,即test。
查看文件夹、文件是否存在
os.path.exists(path) # ->True/False
# 如果文件夹和文件同名,无法知晓检查的是文件还是文件夹(一般不会出现这种情况,检查文件肯定要带文件扩展名的)
os.path.isfile(path) # ->True/False
# 只能用于检查文件的path
is_exist = pathlib.Path(path) # ->True/False
# 检查文件和文件夹的path是否存在
try:
f = open(path)
f.close()
except IOError:
print('file is not exist!')