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

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 模块修改文件的权限和时间戳:chmod utime 函数
import stat, time
# copy mode and timestamp
st = 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 down
os.chdir("tinit")  #os.getcwd()='/home/trade/tinit'
# go back up
os.chdir(os.pardir)  #os.getcwd()='/home/trade'
removedirs 函数会删除所给路径中最后一个目录下所有的空目录.  mkdir  rmdir 函数只能处理单个目录级. 
使用os 模块创建/删除多个目录级:makedirsremovedirs 函数
os.makedirs("test/multiple/levels")
# remove the file
os.remove("test/multiple/levels/file")
# and all empty directories above it
os.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 sys
def 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 string
def 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:
            pass
run("python", "hello.py")
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值