os模块:处理文件,文件夹,进程

来源:互联网 发布:js删除video节点 编辑:程序博客网 时间:2024/05/29 10:36

os模块:处理文件,文件夹,进程.

1.处理文件

使用os模块重命名和删除文件

# remove old backup file, if any
    os.remove(back)
    # rename original to backup...
    os.rename(file, back)
文件的属性

stat函数可以用来获取一个存在文件的信息,它返回一个类元组对象(stat_result对象,包含 10 个元素), 依次是st_mode (权限模式), st_ino (inodenumber), st_dev (device), st_nlink (number of hard links), st_uid (所有者用户 ID), st_gid (所有者所在组 ID ), st_size (文件大小,字节), st_atime (最近一次访问时间), st_mtime (最近修改时间), st_ctime (平台相关; Unix下的最近一次元数据/metadata修改时间,或者 Windows 下的创建时间)

使用os模块修改文件的权限和时间戳:chmodutime 函数

import stat, time# copy mode and timestampst = os.stat(infile)os.chmod(outfile, stat.S_IMODE(st[stat.ST_MODE]))os.utime(outfile, (st[stat.ST_ATIME], st[stat.ST_MTIME]))
 

2. 处理目录

使用os列出目录下的文件:listdir

for file in os.listdir("samples"):    print file

使用os模块改变当前工作目录:getcwd chdir函数

# where are we?cwd = os.getcwd()  #'/home/trade'# go downos.chdir("tinit")  #os.getcwd()='/home/trade/tinit'# go back upos.chdir(os.pardir)  #os.getcwd()='/home/trade'removedirs 函数会删除所给路径中最后一个目录下所有的空目录.  mkdir  rmdir 函数只能处理单个目录级. 

使用os模块创建/删除多个目录级:makedirsremovedirs函数

os.makedirs("test/multiple/levels")# remove the fileos.remove("test/multiple/levels/file")# and all empty directories above itos.removedirs("test/multiple/levels")

使用os模块创建/删除目录:mkdir rmdir函数

os.mkdir("test")os.rmdir("test")如果需要删除非空目录, 你可以使用shutil模块中的rmtree函数.
 

3. 处理进程

使用os执行操作系统命令:调用系统的shell

if os.name == "nt":    command = "dir"else:    command = "ls -l"os.system(command)

使用os模块调用其他程序(Unix)

import sysdef run(program, *args):    pid = os.fork()    if not pid:        os.execvp(program, (program,) +  args)    return os.wait()[0]run("python", "hello.py")

使用os模块(前台或后台)调用其他程序 (Windows)

import stringdef run(program, *args):    # find executable    for path in string.split(os.environ["PATH"], os.pathsep):        file = os.path.join(path, program) + ".exe"        try:           return os.spawnv(os.P_WAIT, file, (file,) + args)  #前台运行
         #return os.spawnv(os.P_NOWAIT, file, (file,) + args)#后台运行        except os.error:            passrun("python", "hello.py")
0 0
原创粉丝点击