#!/usr/bin/env python # coding: utf-8 # # 模块os:与操作系统进行交互 # In[1]: import os # ## 文件相关操作 # 当前工作目录: # In[2]: os.getcwd() # 当前工作目录符号: # In[3]: os.curdir # 当前目录下得的文件: # In[4]: os.listdir(os.curdir) # 生成一个新文件: # In[5]: with open("test.file", "w") as f: pass # In[6]: "test.file" in os.listdir(os.curdir) # 重命名文件: # In[7]: os.rename("test.file", "test.file.new") # In[8]: "test.file" in os.listdir(os.curdir) # In[9]: "test.file.new" in os.listdir(os.curdir) # 删除文件: # In[10]: os.remove("test.file.new") # ## 系统常量 # 当前操作系统的换行符: # In[11]: os.linesep # 当前操作系统的路径分隔符: # In[12]: os.sep # 当前操作系统的环境变量PATH中的分隔符: # In[13]: os.pathsep # 环境变量: # In[14]: os.environ # ## os.path模块 # # 在不同的操作系统下进行操作时,不同的路径规范可能会带来一定的麻烦。Python提供了os.path子模块解决这个问题。 # # os.path是os模块下的一个子模块,它有很多与路径相关的功能,比如对文件路径属性的判断: # - `os.path.isfile(path)`:检测路径是否为文件。 # - `os.path.isdir(path)`:检测路径是否为文件夹。 # - `os.path.exists(path)`:检测路径是否存在。 # - `os.path.isabs(path)`:检测路径是否为绝对路径。 # # os.path模块最主要的功能还是路径分隔符相关的操作。 # Window的路径分隔符是“\”,而Linux/Mac的路径分隔符是“/”,需要合成或者分开路径时,不同的操作系统下所产生的路径不同,可以用os.path模块统一解决这个问题: # # - `os.path.join(a, *p)`:使用系统分隔符,将各个部分合并为一个路径。 # - `os.path.join(a, *p)`:使用系统分隔符,将各个部分合并为一个路径。 # # 例如,os.path.join("test", "a.txt")在Windows系统下会变成: # ``` # test\a.txt # ``` # 在Linux/Mac系统下会变成 # ``` # test/a.txt # ``` # In[ ]: