Home  >  Article  >  Backend Development  >  os module

os module

巴扎黑
巴扎黑Original
2017-06-23 16:26:291290browse

一、简介

Python的标准库中的os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。

二、具体模块

2.1 os.getcwd():获取当前工作目录

# windows
>>> os.getcwd()
'G:\\python'         # \\ 转义路径分隔符 \

#Linux
>>> os.getcwd()
'/root/monitor'

2.2 os.chdir("dirname"): 改变当前工作目录

# windows
>>> os.chdir(r"G:\python\untitled")  # r 转义
>>> os.getcwd()
'G:\\python\\untitled'

#Linux
>>> os.chdir('/usr/local')
>>> os.getcwd()
'/usr/local'

2.3 os.curdir:  返回当前目录,'.'

2.4 os.pardir:  返回当前目录的父目录 , '..'

>>> import os
>>> os.curdir
'.'
>>> os.pardir
'..'

 

2.5 os.makedirs('dirname1/dirname2'):可生成多层递归目录

os.makedirs(r'G:\a\b\c')

  

2.6 os.mkdir('dirname') : 只能一层一层建目录

2.7 os.removedirs('dirname1/dirname2'): 若目录为空则删除,并返回到上一层,若也为空,同样删除,依次类推

 os.removedirs(r'G:\a\b\c')

 

2.8 os.rmdir('dirname') : 删除单级空目录,若目录不为空,无法删除

2.9 os.listdir('dirname'): 列出指定目录下的文件和目录,包括隐藏文件,以列表形式

>>> os.listdir(r'G:\python')
['install', 'program', 'pychart', 'scripts', 'untitled']

  

2.10 os.remove():删除一个文件

2.11 os.rename('oldname','newname') : 重命名文件/目录

2.12 os.stat('path/filename') : 获取文件信息

2.13 os.sep : 输出操作系统下的路径分割符,win下位'\' ,linux 下位'/'

2.14 os.linesep :  操作系统的行终止符,win下位'/r/n',linux下位'\n'

2.15 os.pathsep :  输出用于分割文件路径的字符串

2.16 os.environ : 环境变量,以字典形式

2.17 os.system :  运行shell

2.18 os.path

# os.path.abspath(path)  当前文件的绝对路径
>>> os.path.abspath('111')
'G:\\python\\scripts\\111'

# os.path.split(path) :  将path分成目录和文件名二元组
>>> os.path.split(r'G:\python\scripts\111')
('G:\\python\\scripts', '111')

# os.path.dirname(path)  返回path的目录,其实就是os.path.split第一个元素
>>> os.path.dirname(r'G:\python\scripts\111')
'G:\\python\\scripts'

#os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素

>>> os.path.basename(r'G:\python\scripts\111')
'111'

#os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False

# os.path.isabs(path)  如果path是绝对路径,返回True

#os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False

#os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False

#os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略


#os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间

#os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

  

The above is the detailed content of os module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn