os 模块——操做系统的各类接口
经常使用函数:html
os.path.join(path,*paths)
(经常使用,设置文件路径)将一个或者多个路径链接起来。python
PATH_TO_TEST_IMAGES_DIR = 'test_images/Parking_data_no_modify' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image1.jpg' ] print TEST_IMAGE_PATHS >>> test_images/Parking_data_no_modify/image1.jpg
path.basename(path)
返回 path 路径名的基的名称(即输出路径中经过‘/’ 分割后的最后一项)。这是经过将path参数传递给 split()函数, 而后返回最后一个元素函数
print(os.path.basename(PATH_TO_TEST_IMAGES_DIR) ) >>>Parking_data_no_modify print(os.path.basename(TEST_IMAGE_PATHS) ) >>>image1.jpg
os.path.dirname(path)
返回 path中的目录名.其实是经过将path参数传递个 split()函数, 返回值除去最后一项的前面的部分.(正好和os.path.basename互补)ui
print(os.path.dirname(PATH_TO_TEST_IMAGES_DIR) ) >>> test_images print(os.path.dirname(TEST_IMAGE_PATHS) ) >>>test_images/Parking_data_no_modify
os.path.isfile(path)
若是路径是现有的文件(即真实存在的文件),则返回True。spa
os.path.isfile('/home/ershisui/download/vcr.zip') >>>True(目录download 下确实存在 vcr.zip 文件)
os.path.isdir(path)
若是文件是现有的目录(即真实存在的路径),则返回True。操作系统
os.path.isfile('/home/ershisui/download') >>>True(目录download 确实存在)
os.path.split(path)
Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. 尾部分不会包含斜杠;若是路径以斜线结尾,则尾将为空。若是path中没有斜线,head将为空。若是path为空,head 和 tail
两个都将为空。尾部的斜线会从head中去除掉,除非它是根目录(只包含一个或多个斜线的目录)。在全部状况下,join(head, tail)返回与path相同位置的路径字符串可能不一样)。code
os.path.split(PATH_TO_TEST_IMAGES_DIR) >>>('test_images', 'Parking_data_no_modify') os.path.split(TEST_IMAGE_PATHS) >>>('test_images/Parking_data_no_modify', 'image1.jpg')
os.path.abspath(path)
返回路径名path的规范化的绝对路径。component
os.path.abspath( '.') >>>'/home/ershisui/document/python/Firstry'
打开 file 并返回一个相应的 文件对象.若是文件不能被打开, 抛出 OSError 异常.
参数 mode 是指明打开文件的模式。默认值是'r',表示使用文本的方式打开文件来读取。htm
for line in open('parking_space_select.txt'): print(line) >>>1 5 0.0520833 0.235937 0.14375 0.353125 0.0270833 0.353125 0.110417 0.484375 0.00833333... 2 5 0.229167 0.496875 0.752083 0.785937 0.075 0.229687 0.19375 0.5 0.00416667 0.373437 0.0479167...
os.listdir(path = '.')
返回一个list,包含给定path 目录下全部条目的名字。该list是任意顺序,不包括特殊条目'.'以及'..',即便它们存在于目录中。对象
os.listdir('.') >>>['detection_landmark.py', '1.jpg', 'test1.py', 'Untitled.ipynb', 'test.py', 'face_recognition.py', 'fr.py', '.ipynb_checkpoints']
os.getcwd()
获得当前的工做目录
os.getcwd() >>>'/home/ershisui/document/python/Firstry'
os.mkdir(path)
建立目录(若提供的不是绝对路径,则默认为在当前目前下建立)。
os.mkdir('hello') >>> (在当前目录下生成文件夹名为 hello) os.mkdir('/home/ershisui/document/hello')
os.rmdir(path)
删除指定目录(若提供的不是绝对路径,则默认为在当前目前下建立)。仅当目录为空时才有效。
os.rmdir('hello') os.rmdir('/home/ershisui/document/hello')
os.remove(path)
删除指定文件
os.remove('1.jpg')
os.chdir(path)
改变目录到指定目录
os.chdir('/home/ershisui/download') os.getcwd() >>> '/home/ershisui/download'
参考: 博客:http://www.cnblogs.com/kaituorensheng/archive/2013/03/18/2965766.html
python 中文文档:
http://python.usyiyi.cn/documents/python_352/library/os.html#os-file-dir
http://python.usyiyi.cn/documents/python_352/library/os.path.html#module-os.path