操作系统服务:OS模块

http://blog.csdn.net/pipisorry/article/details/52454486

一般的操作系统服务之OS模块Generic Operating System Services

os模块

模块包含普遍的操作系统功能。利用这个模块可以写出与平台无关的程序,比如就是使用os.sep可以取代操作系统特定的路径分割符。

os模块包含

    Tasks    Tools
    Shell variables    os.environ
    Running programs    os.system, os.popen, os.execv, os.spawnv
    Spawning processes    os.fork, os.pipe, os.waitpid, os.kill
    Descriptor files, locks    os.open, os.read, os.write
    File processing    os.remove, os.rename, os.mkfifo, os.mkdir, os.rmdir
    Administrative tools    os.getcwd, os.chdir, os.chmod, os.getpid, os.listdir, os.access
    Portability tools    os.sep, os.pathsep, os.curdir, os.path.split, os.path.join
    Pathname tools    os.path.exists('path'), os.path.isdir('path'), os.path.getsize('path')

[

]

os模块常用的方法

1.os.sep                    可以取代操作系统特定的路径分割符
2.os.name                 字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
3.os.getenv()             用来读取环境变量

6.os.putenv()             用来设置环境变量 。推荐用os.environ,因为使用os.putenv()并不会真正改变os.environ字典里面的环境变量,即某些平台无效,但是使用os.environ有一个潜在的隐患:在一些平台上,包括FreeBSD和Mac OS X,修改environ会导致内存泄露。

os.environ['环境变量名称']='环境变量值' #其中key和value均为string类型

os.putenv('环境变量名称', '环境变量值')

9.os.system()             函数用来运行shell命令 [python中调用命令行命令]
10.os.linesep               字符串给出当前平台使用的行终止符。例如,Windows使用'/r/n',Linux使用'/n'而Mac使用'/r'。

11. os.access   os.chmod

判断并修改文件读写权限

    try:

        if not os.access(src, os.W_OK):

            os.chmod(src,0664)

    except:

        print'Error: you can not chang %s\'s mode.'%src
12 os.getlogin()
        python如何获取当前shell、终端的用户名。os.getlogin() returns the name of the "user logged in on the controlling terminal of the process."能获取当前桌面登录的用户名;用户登录服务器的用户名;nologin如在pycharm中直接执行的可能会报错:OSError: [Errno 25] Inappropriate ioctl for device或者返回'_reportmemoryexception'。

        最好是这样取得用户名:pwd.getpwuid(os.geteuid()).pw_name 或者 pwd.getpwuid( os.getuid() )[ 0 ]

        其它方式:os.environ.get('USERNAME') or os.environ.get('USER'),但是有问题,it's not going to be safe because environment variables can be changed.

[Is there a portable way to get the current username in Python?]

os — Files and Directories

[Files and Directories*]

os.getcwd()

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

Return a string representing the current working directory. Availability: Unix, Windows.

os.curdir                返回但前目录('.')
os.chdir(dirname)  改变工作目录到dirname

os.listdir(path)              

 返回指定目录下的所有文件和目录名(不包括子目录中的文件名)

Note:listdir会将保护的操作系统文件list出来,如windows下的desktop.ini文件

Return a list containing the names of the entries in the directory. The list is in arbitrary order. It does not include the special entries ’.’ and ’..’ even if they are present in the directory. Availability: Unix,Windows. Changed in version 2.3: OnWindows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects.

os.mkdir(pathmode=0o777*dir_fd=None)

创建目录(不能包含子目录)

os.makedirs(namemode=0o777exist_ok=False)

递归地创建目录(包含子目录)

os.makedirs("./input", exist_ok=True) #可以使用相对路径

exist_ok=True则如果目录或文件不存在则创建,否则不创建,相当于加了一个exist判断。

Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. Throws an error exception if the leaf directory already exists or cannot be created. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
Note: makedirs() will become confused if the path elements to create include os.pardir. New in version 1.5.2.Changed in version 2.3: This function now handles UNC paths correctly.

os.walk(top, [topdown=True, [οnerrοr=None, [followlinks=False]]])

os.walk是一个generator函数。Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames,filenames).......每次可以得到一个三元tupple,其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。

示例1

>>> x=os.walk('/home/tiny/workspace/py')
>>>for i in x:
... i
('/home/tiny/workspace/py', ['2', '1'], ['.allfile.py.swp', 'allfile.py', 'list_get.py', 'test.py', 'tags', 'log.txt'])
('/home/tiny/workspace/py/2', [], ['fib.py', 'djcoding.py', 'drectory_travel.py', 'foo.py'])
('/home/tiny/workspace/py/1', [], ['timetest2.py', 'timetest.py'])

示例2

获取当前目录下所有文件名(包括相对路径)
for root, ds, fs in os.walk(file_dir):
    for f in fs:
        fullname = os.path.join(root, f)
        print(fullname)

os.rmdir(path, *, dir_fd=None)

Remove (delete) the directory path. Only works when the directory isempty, otherwise, OSError is raised.

os.removedirs(name)

递归删除空目录(包括父目录),子目录非空出错。
递归删除目录(所有子目录,包容非空子目录):if os.path.exists(self.log_dir): shutil.rmtree(self.log_dir)

windows下莫名其妙报错OSError: [WinError 145] 目录不是空的。: './tmp/log/'

[shutil.rmtree(path, ignore_errors=False, οnerrοr=None)]

os.remove(path, *, dir_fd=None)

删除文件:Remove (delete) the file path. If path is a directory, OSError israised.

os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)

修改文件权限

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases.

python批量重命名文件

for basename in listdir(filedir):
    rename(join(filedir, basename), join(filedir, basename.split('.')[0]))

目录和文件操作os.path — Common pathname manipulations

 [os.path — Common pathname manipulations]

都是和路径指定的文件,目录,和路径字符串有关系的函数

os.path.isdir(name)           判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name)           判断name是不是一个文件,不存在name也返回false

os.path.islink(name)         判断nama是不是一个链接文件
os.path.exists(name)         判断是否存在文件或目录name
os.path.getsize(name)       获得文件大小,如果name是目录返回0L
os.path.abspath(name)     获得绝对路径

os.path.realpath 获取文件绝对路径

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

os.path.join(path1, [path2, [...]])   连接目录与文件名或目录

Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that onWindows, since there is a current directory for each drive,os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

Note: 不能使用os.path.join('a/b', '/c'),会直接返回'/c'。

os.path.dirname(path)

       返回文件路径 Return the directory name of pathname path. This is the first half of the pair returned by split(path).Note that the result of this function is different from the Unix basename program; where basename for ’/foo/bar/’ returns ’bar’, the basename() function returns an empty string (”).

s = 'a/b/c'
os.path.dirname(s)
Out[4]: 'a/b'
s = 'a/b/c/'
os.path.dirname(s)
Out[6]: 'a/b/c'

获得绝对路径

os.path.abspath(name)
realpath = os.path.realpath(filename)
print realpath
# output
# C:\xxx\pyfunc\test.txt

os.path.split()

返回一个路径的目录名和文件名。分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)

os.path.split('/home/shirley/myself/code/icbc.txt')  

('/home/shirley/myself/code', 'icbc.txt')  

Note:path.split()中目录参数对结果的影响

print(path.split(r'E:\mine\java_workspace\AMC_master\Data\Input\corpus_NP'))

返回('E:\\mine\\java_workspace\\AMC_master\\Data\\Input', 'corpus_NP'),而

print(path.split(r'E:\mine\java_workspace\AMC_master\Data\Input\corpus_NP/'))

返回('E:\\mine\\java_workspace\\AMC_master\\Data\\Input\\corpus_NP', '')

os.path.splitext(path) 分离文件名与扩展名
Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored;
splitext(’.cshrc’) returns (’.cshrc’, ”). Changed in version 2.6: Earlier versions could produce an empty root when the only period was the first character.

OS系统模块获取路径

获得Python脚本所在目录的位置

获取绝对路径目录的3种方式:脚本文件所在目录的绝对路径。

cur_dir = os.path.dirname(os.path.abspath(__file__))
cur_dir = os.path.dirname(os.path.realpath(__file__))
cur_dir = os.path.split(os.path.realpath(__file__))[0]

示例和应用

1 为了避免相对引入的错误,可以先将dir目录的父目录加到path中

sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../..'))

再直接引入目录dir。

2 如果不是绝对路径的时候,相对路径可能打开文件失败,出错:FileNotFoundError: [Errno 2] No such file or directory: 'data/English_stopwords.txt'。原因是data/patterns.txt是相对当前.py文件的路径,而如果当前执行文件不是它,而是别的py文件调用这个函数,那么那个相对路径就是相对别的py文件而言的,就会找不到路径。

real_dir = os.path.split(os.path.realpath(__file__))[0]
model_path_name = os.path.join(real_dir, model_path_name)

获得运行的程序的当前目录

os.getcwd()

如果是要获得运行的程序的当前目录所在位置,那么可以使用os模块的os.getcwd()函数。

Note:这个即使在被调用的某个脚本上写,返回的也是调用方的位置。

sys.path[0]和sys.argv[0]

如果是要获得当前执行的脚本的所在目录位置,那么需要使用sys模块的sys.path[0]变量或者sys.argv[0]来获得。实际上sys.path是Python会去寻找模块的搜索路径列表,sys.path[0]和sys.argv[0]是一回事,因为Python会自动把sys.argv[0]加入sys.path。
示例:

在C:\test目录下执行python getpath\getpath.py,那么os.getcwd()会输出“C:\test”,sys.path[0]会输出“C:\test\getpath”。
更特别地,如果你用py2exe模块把Python脚本编译为可执行文件,那么sys.path[0]的输出还会变化。
如果把依赖库用默认的方式打包为zip文件,那么sys.path[0]会输出“C:\test\getpath\libarary.zip”;
如果在setup.py里面指定zipfile=None参数,依赖库就会被打包到exe文件里面,那么sys.path[0]会输出“C:\test\getpath\getpath.exe”。
但以上这些其实都不是
C:\test

----sub/

    ----sub_path.py

----getpath.py

getpath.py调用sub_path.py;我们在C:\test下执行getpath.py。如果想得到sub_path.py的路径,那么可以在sub_path.py中取os.path.split(os.path.realpath(__file__))[0],其中__file__虽然是所在.py文件的完整路径,但是这个变量有时候返回相对路径,有时候返回绝对路径,因此还要用os.path.realpath()函数来处理一下。os.path.realpath(__file__)输出是“C:\test\sub\sub_path.py”,而os.path.split(os.path.realpath(__file__))[0]输出才是“C:\test\sub”。

文件执行路径、目录

pathname=os.path.dirname(sys.executable)

from: http://blog.csdn.net/pipisorry/article/details/52454486

ref: [python文件、目录及路径操作-获取当前python文件的路径]

[16. Generic Operating System Services]

[16.1. os — Miscellaneous operating system interfaces]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值