python os 模块

浅浅的花香味﹌ 2022-08-09 05:29 72阅读 0赞

转载自:http://www.cnblogs.com/BeginMan/p/3327291.html

一、os模块概述

Python os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。(一语中的)

二、常用方法

1、os.name

输出字符串指示正在使用的平台。如果是window 则用’nt’表示,对于Linux/Unix用户,它是’posix’。

2、os.getcwd()

函数得到当前工作目录,即当前Python脚本工作的目录路径。

3、os.listdir()

返回指定目录下的所有文件和目录名。

  1. >>> os.listdir(os.getcwd())
  2. ['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe']
  3. >>>

4、os.remove()

删除一个文件。

5、os.system()

运行shell命令。

  1. >>> os.system('dir')
  2. 0
  3. >>> os.system('cmd') #启动dos

6、os.sep 可以取代操作系统特定的路径分割符。

7、os.linesep字符串给出当前平台使用的行终止符

复制代码

  1. >>> os.linesep
  2. '\r\n' #Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
  3. >>> os.sep
  4. '\\' #Windows
  5. >>>

复制代码

8、os.path.split()

函数返回一个路径的目录名和文件名

  1. >>> os.path.split('C:\\Python25\\abc.txt')
  2. ('C:\\Python25', 'abc.txt')

9、os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

  1. >>> os.path.isdir(os.getcwd())
  2. True
  3. >>> os.path.isfile('a.txt')
  4. False

10、os.path.exists()函数用来检验给出的路径是否真地存在

复制代码

  1. >>> os.path.exists('C:\\Python25\\abc.txt')
  2. False
  3. >>> os.path.exists('C:\\Python25')
  4. True
  5. >>>

复制代码

11、os.path.abspath(name):获得绝对路径

12、os.path.normpath(path):规范path字符串形式

13、os.path.getsize(name):获得文件大小,如果name是目录返回0L

14、os.path.splitext():分离文件名与扩展名

  1. >>> os.path.splitext('a.txt')
  2. ('a', '.txt')

15、os.path.join(path,name):连接目录与文件名或目录

复制代码

  1. >>> os.path.join('c:\\Python','a.txt')
  2. 'c:\\Python\\a.txt'
  3. >>> os.path.join('c:\\Python','f1')
  4. 'c:\\Python\\f1'
  5. >>>

复制代码

16、os.path.basename(path):返回文件名

复制代码

  1. >>> os.path.basename('a.txt')
  2. 'a.txt'
  3. >>> os.path.basename('c:\\Python\\a.txt')
  4. 'a.txt'
  5. >>>

复制代码

17、os.path.dirname(path):返回文件路径

  1. >>> os.path.dirname('c:\\Python\\a.txt')
  2. 'c:\\Python'

发表评论

表情:
评论列表 (有 0 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python os.path模块

    join:连接字符串数组。 将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 os.path.join():  将多个路径组合后