Python入门:os部分方法介绍(一)

来源:互联网 发布:未定义数组索引 编辑:程序博客网 时间:2024/05/21 17:03

>>> help(os)

Help on module os:

NAME
os - OS routines for Mac, NT, or Posix depending on what system we’re on.
os顾名思义就是有关操作系统的相关操作


#cwd = Current Working Directory(当前工作目录)>>> help(os.getcwd)Help on built-in function getcwd in module posix:getcwd(...)    getcwd() -> path    Return a string representing the current working directory.
>>> os.getcwd()'/Users/frankslg/PycharmProjects/untitled'
>>> help(os.listdir)Help on built-in function listdir in module posix:listdir(...)    listdir(path) -> list_of_strings    #需要传入一个参数‘path’,这个path就可以是从别的地方传入的,也可以是自己写的,当然也可以是当前文件所在的目录    Return a list containing the names of the entries in the directory.    #返回一个列表包含传入的目录名中的所有内容        path: path of directory to list    The list is in arbitrary order.  It does not include the special entries '.' and '..' even if they are present in the directory.    #这个列表是任意顺序的。它不包括特殊‘.’和‘..’,即使存在当前目录中
>>> os.listdir(os.getcwd())['.idea', 'test.py', 'test1.py']

以上两个方法特别有用,在很多场合都可以使用,比如:需要列出当前文件所在目录的所有文件怎么办?列出所有文件能干什么?可以做文件查找脚本!!!可以新建文件、删除文件等等!!!

>>> os.name'posix'

os.name输出当前平台。如果是window 则用’nt’表示,对于Linux/Unix/mac用户,它是’posix’。

>>> os.listdir(os.getcwd())['.idea', '123', 'test.py', 'test1.py']>>> os.remove('123')#删除‘123’这个文件>>> os.listdir(os.getcwd())['.idea', 'test.py', 'test1.py']

执行系统命令

>>> os.system('ls')123test.pytest1.py0

系统的路径分隔符和行终结符。不同系统不一样,windows是‘\’和‘\r\n’,类unix系统如下:

>>> os.sep'/'>>> os.linesep'\n'

注:这在很多脚本中都很重要,需要开发一个可移植性的脚本,就需要判断这些信息,以做到不同操作系统的相同处理结果

>>> os.path.split(os.getcwd())('/Users/frankslg/PycharmProjects', 'untitled')#返回当前文件所在的路径和当前文件名

os.path.isfile #判断是不是文件
os.path.isdir #判断是不是目录
os.path.exists #判断存在不存在
……
拼接新的目录

>>> os.path.join('/tmp/','123')'/tmp/123'

获取文件后缀名

>>> os.path.splitext('/tmp/123.txt')('/tmp/123', '.txt')>>> os.path.splitext('123.txt')('123', '.txt')

等等……!!!

0 0
原创粉丝点击