30 os模块

1.当前路径及路径下的文件

os.getcwd():查看当前所在路径。

os.listdir(path):列举目录下的所有文件。返回的是列表类型。

>>> import os
>>> os.getcwd()
'D:\\pythontest\\ostest'
>>> os.listdir(os.getcwd())
['hello.py', 'test.txt']

2.绝对路径

os.path.abspath(path):返回path的绝对路径。

>>> os.path.abspath('.')
'D:\\pythontest\\ostest'
>>> os.path.abspath('..')
'D:\\pythontest'

3.查看路径的文件夹部分和文件名部分

os.path.split(path):将路径分解为(文件夹,文件名),返回的是元组类型。可以看出,若路径字符串最后一个字符是\,则只有文件夹部分有值;若路径字符串中均无\,则只有文件名部分有值。若路径字符串有\,且不在最后,则文件夹和文件名均有值。且返回的文件夹的结果不包含\.

os.path.join(path1,path2,...):将path进行组合,若其中有绝对路径,则之前的path将被删除。

复制代码
>>> os.path.split('D:\\pythontest\\ostest\\Hello.py')
('D:\\pythontest\\ostest', 'Hello.py')
>>> os.path.split('.')
('', '.')
>>> os.path.split('D:\\pythontest\\ostest\\')
('D:\\pythontest\\ostest', '')
>>> os.path.split('D:\\pythontest\\ostest')
('D:\\pythontest', 'ostest')
>>> os.path.join('D:\\pythontest', 'ostest')
'D:\\pythontest\\ostest'
>>> os.path.join('D:\\pythontest\\ostest', 'hello.py')
'D:\\pythontest\\ostest\\hello.py'
>>> os.path.join('D:\\pythontest\\b', 'D:\\pythontest\\a')
'D:\\pythontest\\a'
复制代码

 os.path.dirname(path):返回path中的文件夹部分,结果不包含'\'

复制代码
>>> os.path.dirname('D:\\pythontest\\ostest\\hello.py')
'D:\\pythontest\\ostest'
>>> os.path.dirname('.')
''
>>> os.path.dirname('D:\\pythontest\\ostest\\')
'D:\\pythontest\\ostest'
>>> os.path.dirname('D:\\pythontest\\ostest')
'D:\\pythontest'
复制代码

 os.path.basename(path):返回path中的文件名。

复制代码
>>> os.path.basename('D:\\pythontest\\ostest\\hello.py')
'hello.py'
>>> os.path.basename('.')
'.'
>>> os.path.basename('D:\\pythontest\\ostest\\')
''
>>> os.path.basename('D:\\pythontest\\ostest')
'ostest'
复制代码

4.查看文件时间

 os.path.getmtime(path):文件或文件夹的最后修改时间,从新纪元到访问时的秒数。

 os.path.getatime(path):文件或文件夹的最后访问时间,从新纪元到访问时的秒数。

 os.path.getctime(path):文件或文件夹的创建时间,从新纪元到访问时的秒数。

>>> os.path.getmtime('D:\\pythontest\\ostest\\hello.py')
1481695651.857048
>>> os.path.getatime('D:\\pythontest\\ostest\\hello.py')
1481687717.8506615
>>> os.path.getctime('D:\\pythontest\\ostest\\hello.py')
1481687717.8506615

5.查看文件大小

  os.path.getsize(path):文件或文件夹的大小,若是文件夹返回0。

>>> os.path.getsize('D:\\pythontest\\ostest\\hello.py')
58L
>>> os.path.getsize('D:\\pythontest\\ostest')
0L

6.查看文件是否存在

 os.path.exists(path):文件或文件夹是否存在,返回True 或 False。

复制代码
>>> os.listdir(os.getcwd())
['hello.py', 'test.txt']
>>> os.path.exists('D:\\pythontest\\ostest\\hello.py')
True
>>> os.path.exists('D:\\pythontest\\ostest\\Hello.py')
True
>>> os.path.exists('D:\\pythontest\\ostest\\Hello1.py')
False
复制代码

7.一些表现形式参数

os中定义了一组文件、路径在不同操作系统中的表现形式参数,如:

复制代码
>>> os.sep
'\\'
>>> os.extsep
'.'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
复制代码

猜你喜欢

转载自www.cnblogs.com/jeavy/p/9253803.html
30