Python学习笔记之读取文件、OS模块、异常处理、with as语法示例

转:https://m.sogou.com/web/id=4c468b90-3f64-418c-acf8-990b5fe2a757/keyword=python%20os%E6%A8%A1%E5%9D%97%E8%AF%BB%E5%8F%96%E8%AE%B0%E4%BA%8B%E6%9C%AC%E5%86%85%E5%AE%B9/sec=4NxQ7Q1PJSfDB2N8MPATLA../tc?clk=5&url=https%3A%2F%2Fwww.jb51.net%2Farticle%2F162468.htm&pid=sogou-clse-2996962656838a97&e=1427&de=1&dp=1&rcer=gXdGqO_Po_Z6XqxOP&is_per=0&pno=1&vrid=30000000&wml=0&linkid=summary&clickTime=1609212904959&mcv=44&pcl=348,1428&sed=0&ml=9&sct=142

文件读取 #读取文件 f = open("test.txt","r") print(f.read()) #打印文件内容 #关闭文件 f.close()   获取文件绝对路径:OS模块   os.environ["xxx"] 获取系统环境变量   os.getcwd 获取当前python脚本工作路径   os.getpid() 获取当前进程ID   os.getppid() 获取父进程ID   异常 #读取文件 f = None try:   f = open("test.txt", "r")   print(f.read()) except BaseException:   print("文件没有找到") finally:   if f is not None:   f.close()   with as语法 #读取文件 with open("test.txt","r") as f:   print(f.read())   f.close()

  

posted @ 2020-12-29 21:56  tigergaonotes  阅读(183)  评论(0编辑  收藏  举报