Python标准库之os模块

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python标准库之os模块相关的知识,希望对你有一定的参考价值。

1、删除和重命名文件

import os
import string

def replace(file, search_for, replace_with):
    # replace strings in a text file

    back = os.path.splitext(file)[0] + ".bak"                            (1)
    temp = os.path.splitext(file)[0] + ".tmp"

    try:
        # remove old temp file, if any
        os.remove(temp)                                                  (2)
    except os.error:
        pass                                                            

    fi = open(file)
    fo = open(temp, "w")                                                 (3) 

    for s in fi.readlines():
        fo.write(string.replace(s, search_for, replace_with))            (4)

    fi.close()
    fo.close()

    try:
        # remove old backup file, if any
        os.remove(back)
    except os.error:
        pass

    # rename original to backup...
    os.rename(file, back)                                                (5)  

    # ...and temporary to original
    os.rename(temp, file)

#
# try it out!

file = "samples/sample.txt"

replace(file, "hello", "tjena")
replace(file, "tjena", "hello")

(1)os.path.splitext(filename)会分解出文件名和扩展名,并保存在一个元组里。而os.path.split(path)则会把路径分解为目录名和文件名,同样保存在元组里。

(2)os.remove(file)会删除file文件。

(3)w表示只写,其他的,r表示只读,r和w读写的是文本。b表示二进制,因而rb表示对二进制文件只读,wb表示对二进制文件只写,读写的二进制文件通常后缀名是dat。

(4)string.replace(s, old, new,maxsplit)会将s字符串中的所有old部分替换成new。其中,maxsplit为可选参数,用来控制替换的个数,举个例子:

>>>import string
>>>s = ‘abc abcc abccc‘
>>>string.replace(s, ‘c‘, ‘d‘)
‘abd abdd abddd‘
>>>string.replace(s, ‘c‘, ‘d‘, 2)
‘abd abdc abccc‘

(5)os.rename(old, new) 会将old文件的文件名替换成new。

2、列出目录下的文件

os模块下的listdir 函数会返回给定目录中所有文件名(包括目录名)组成的列表。

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

sample.au
sample.jpg
sample.wav
...

os.listdir() 括号内即目录名(可以把目录理解为文件夹)。需要注意,目录名是作为关键字传入的,是一个字符串,因此必须在目录名两边加上引号。另外,如果目录名不在当前的工作目录下,则必须写出该目录的绝对路径,如D:/xx/xx/samples ,否则python将找不到该目录。

3、获取和改变当前工作目录

os.getcwd()可以获取当前的工作目录,os.chdir()则是用来改变当前的工作目录。以我的电脑为例:

>>>import os
>>>os.getcwd()
‘C:\\Python27‘
>>>os.chdir(‘C:/Users/Wu/desktop‘)
>>>os.getcwd()
‘C:\\Users\\Wu\\desktop‘

(这里插一句:就我个人的体会来说,如果尝试将函数名和它的功能和联系起来,想一想它的全称,就能够很快地记住这个函数的用处。以getcwd为例,它的功能是获取当前的工作目录,那么cwd就应该是current working directory的缩写。)

4、创建和删除多级目录

makedirs和removedirs函数用于创建和删除多级目录。如在桌面创建和删除exercise目录:

>>>os.makedirs(‘C:/Users/Wu/desktop/exercise‘)
>>>os.removedirs(‘C:/Users/Wu/desktop/exercise‘)

需要注意的几点:
1、removedirs只能删除空目录。其删除方式为:若目录为空,则删除,并递归到上一级目录。如若也为空,则继续删除,直到上一级目录非空。

2、makedirs创建的是多级目录,而mkdir只能创建单个目录,即除创建的这一级目录,它的所有上级目录必须都是存在的,如果不存在,则会发生错误。

3、同样的,相较于removedirs,rmdir函数只能删除单个空目录,但它不会递归到上级目录,检查是否为空并删除。

5、获取文件属性

stat 函数可以用来获取一个存在的文件的信息。os.stat(file) 会返回一个类元组对象(stat_result对象, 包含 10 个元素), 依次是st_mode (权限模式),st_ino (inode number),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 下为创建时间)。需要注意的两点:

1、(st_inode , st_dev)为 Unix 下的为每个文件提供了唯一标识, 但在其他平台是无意义的。

2、st_atime,st_mtime和st_ctime返回的是一串数字,需要用time模块下的ctime函数才能转化成时间。

举个例子:

>>>import os
>>>import time
>>>for i in os.stat(‘C:/Users/Wu/desktop/exercise/hello.py‘):
       print i
33206
0
0
0
0
0
22
1399259008
1399259008
1399259008
>>>time.ctime(1399259008)
‘Mon May 05 11:03:28 2014‘

以上是关于Python标准库之os模块的主要内容,如果未能解决你的问题,请参考以下文章

Python标准库之os模块

Python标准库之os模块

python标准库 —— os模块

Python基础编程——标准库之fileinput与time模块

python标准库之os库

056 模块7-os库的基本使用