您的位置:首页 > 编程语言 > Python开发

Python开发技术详解-笔记_第07章-文件的处理

2013-10-30 19:50 831 查看
第7章 文件的处理



数据的存储可以使用数据库,也可以使用文件.数据库保持了数据的完整性和关联性, 而且数据更安全、可靠.使用文件存储数据则非常简单、易用,不必安装数据库管理让系统等运行环境.文件通常用于存储应用软件的参数或临时性文件.

- 文件的创建、读写、修改

- 文件的拷贝、删除、重命名

- 文件的内容搜索、替换

- 文件的比较

- 配置文件的读写

- 目录的创建、遍历

- 文件 和 流

7.1 文件的基本操作

文件通常用于存储数据或应用系统的参数.Python提供了 os、os.path、shutil等模块用于处理文件.

7.1.1 文件的打开和创建

使用内联模块的函数 file()

(1) 语法

file(name[, mode[, buffering]]) -> file object

open(name[, mode[, buffering]]) -> file object



(2) 说明

name: 文件名, 绝对路径, 写入时如果不存在则创建

mode: 文件打开模式

buffering: 0, 不缓存; 1, 缓存; 大于1, 表示缓存区大小,单位(B)

(3) 文件的打开模式

r 只读, 默认打开方式

r+ 读写 (先读后写,否则会覆盖原位置内容)

w 写入, 先清空文件内容, 无文件则创建

w+ 读写, 先清空文件内容, 无文件则创建

a 写入, 追加, 无文件则创建

a+ 读写, 追加, 无文件则创建

b 二进制模式打开, 可与 r w a + 结合使用

U 支持所有换行符. "\r" "\a" "\r\n"

注: 图片视频等媒体文件必须使用"b"模式打开

(4) file类的常用属性和方法

closed 判断文件是否关闭, 关则True

encoding 显示文件的编码类型

mode 显示文件的打开模式

name 显示文件的名称

newlines 文件使用的换行模式

flush() 把缓存区的内容写入磁盘

close() 关闭文件

read([size]) 读取size个字节作为字符串返回,缺省时读取整个文件

readline([size]) 读行, 返回前size个字节的字符串, 缺省时返回一行

readlines([size])返回列表, 其元素为每行的内容字符串

seek(offset[,whence]) 移动指针,offset偏移量;

whence相对位置:0,文件开头;1,当前位置;2,文件末尾

tell() 返回文件指针当前的位置

next() 返回下一行的内容, 并将指针移到下一行

truncate([size]) 删除size个字节的内容, 默认清空

write(string) 写入string

writelines(sequence)

(5) 文件的处理一般分为以下3个步骤

① open

② read / write

③ close

(6) 举例

# 1.txt 不能存在

>>> f = file("1.txt", "w+")

# 当前文件指针位置

>>> f.tell()

0L

>>> f.read()

''

# 写入

>>> f.write("hello \n world!")

>>> f.tell()

15L

#将指针指向开头

>>> f.seek(0)

>>> f.read()

'hello \n world!'

>>> f.close()

7.1.2 文件的读取

- read() 读整个文件

- readline() 按行读,每次一行

- readlines() 按行读,读所有行

(1) readline()

readline([size]) -> next line from the file, as a string.

Retain newline.

A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then).

Return an empty string at EOF.

每次读一行, 返回字符串, 读到末尾返回空串""

(2) readlines()

readlines([size]) -> list of strings, each a line from the file

Call readline() repeatedly and return a list of the lines so read.

The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.

重复调用readline, 返回列表, 每个元素即为一行内容.

(3) read()

read([size]) -> read at most size bytes, returned as a string.

If the size argument is negative or omitted, read until EOF is reached.

Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.

一次读取全部内容, 字符串返回.

7.1.3 文件的写入

(1) write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.



(2) writelines(seq_of_strs) -> None. Write the strings to the file

Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.



7.1.4 文件的删除

删除 需使用 os 模块 、os.path 模块

os模块提供了对系统环境、文件、目录等操作系统级的接口函数

os.path模块用于处理文件和目录的路径.

(1) os模块 常用的文件处理函数

access(path, mode) 安装mode指定的权限访问文件

chmod(path, mode) 改变文件访问权限.mode用unix系统的权限代号

open(filename,flag[,mode=0777]) 打开文件, 默认读写执行的权限

remove(path) 删除path指定的文件

rename(old,new) 重命名目录/文件

stat(path) 返回文件的所有属性

fstat(path) 返回打开文件的所有属性

lseek(fd,pos,how) 设置文件的当前位置,返回当前位置的字节数

listdir(path) a list of strings

startfile(filepath[,operation]) 启动关联程序打开文件

tmpfile() 创建1个临时文件,位于操作系统的临时目录

(2) os.path模块 常用的函数

abspath(path) 返回path所在的绝对路径

dirname(path) 返回目录的绝对路径

exists(path) 判断文件是否存在

getatime(filename) 返回文件最后访问时间

getctime(filename) 返回文件的创建时间

getmtime(filename) 返回文件最后修改时间

getsize(filename) 返回文件的大小

isabs(s) 测试路径是否为绝对路径

isdir(path) 测试是否为已存在的目录

isfile(path) 测试是否为已存在的文件

split(path) 返回元组(dir,filename)

splitext(path) 返回元组(root, ext)

splitdrive(path) 返回元组(drive,path)

walk(top,func,arg) 遍历目录树, 与 os.walk()类似

7.1.5 文件的复制和移动

(1) read、write

file类没有提供直接复制文件的方法,通过先读后写的方式实现



(2) shutil模块的 copy() 和 move()

① copy(src, dst)

src : 源文件

dst : 目录

② move(src, dst)

src : 文件或目录

7.1.6 文件的重命名

os模块的函数rename()可以对文件或目录进行重命名

glob模块用于路径的匹配,返回符合给定匹配条件的文件列表.

glob(pathname)

Return a list of paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards

>>> glob.glob("E:\desktop\*.txt")

7.1.7 文件内容的查找和替换

结合 字符串的查找和替换

7.1.8 文件的比较

使用 difflib模块 实现对序列、文件的比较

7.1.9 配置文件的访问

使用 ConfigParser模块的 ConfigParser类

(1) 读取配置文件的内容

(2) 将设置的配置项目写入配置文件

(3) 修改配置文件

(4) 配置块和配置项的删除

7.2 目录的基本操作

目录是文件存储的集合,对目录的操作涉及目录的创建、删除、遍历

7.2.1 目录的创建与删除

1)os模块 提供了针对目录进行操作的函数.



2)以下为常用的目录处理函数

mkdir(path[, mode=0777]) 创建一级目录,即一个文件夹

makedirs(path [, mode=0777]) 创建多级目录,即"d1/d2/d3"

rmdir(path) 删除一级目录

removedirs 删除多级目录(中间目录必须是空的)

listdir(path) 返回path目录下的所有文件名列表

getcwd() 返回当前工作目录的string

chdir(path) 改变当前工作目录

walk(top, topdown=True, onerror=None, followlinks=False)遍历目录

返回generator, (curDirStr, subDirList, curDirFilesList)

top 根目录

topdown True, 先文件后子目录; False, 先子目录后文件.

onerror 遍历文件出错时的处理函数

followlinks 是否遍历符号链接指向的文件或目录



3)举例

>>> os.getcwd()

'E:\\desktop\\python2\\07'

>>> os.mkdir("./test")

>>> os.chdir("./test")

>>> os.getcwd()

'E:\\desktop\\python2\\07\\test'

>>> os.mkdir("dir1")

>>> os.listdir(".")

['dir1']

>>> os.rmdir("dir1")

>>> os.listdir(".")

[]

>>> os.makedirs("dir1/dir2/dir3")

>>> os.removedirs("dir1/dir2/dir3")

7.2.2 目录的遍历

- 自定义递归函数 recursion

- os.path.walk()

- os.walk()

(1) 递归函数

E:\desktop\python2\07\recursion.py

(2) os.path.walk(top, func, arg)

top : 要遍历的目录

func : func(arg, dirname, fnames)

- arg : os.path.walk的第三个参数

- dirname : 要遍历的目录

- fnames : dirname下的所有文件及子目录的列表

arg : 传递给func的参数

举例 :

E:\desktop\python2\07\os_path_walk.py

#-*- encoding:UTF-8 -*-
import os
def traverseDir(arg, dirname, fnames):
    for filename in fnames:
        print os.path.join(dirname, filename)

if __name__ == '__main__':
    path = "E:\desktop\python2"
    os.path.walk(path, traverseDir, None)


(3) os.walk()

walk(top, topdown=True, onerror=None, followlinks=False)

返回generator, (curDirStr, subDirList, curDirFilesList)

top : 根目录

topdown : True, 先文件后子目录; False, 先子目录后文件.

onerror : 遍历文件出错时的处理函数

followlinks:是否遍历符号链接指向的文件或目录

举例:



E:\desktop\python2\07\os_walk.py

#-*- encoding:UTF-8 -*-
import os
def traverseDir( dirPath ) :
    for curDirStr,subDirList,curDirFilesList in os.walk(dirPath) :
        for filename in curDirFilesList :
            print os.path.join(curDirStr, filename)

if __name__ == '__main__':
    dirPath = "E:\desktop\python2"
    traverseDir(dirPath)


7.3 文件和流

读写数据的方式有多种,如文件的读写、数据库的读写等.

为了有效地表示数据的读写,把文件、外设、网络连接等数据传输抽象地表示为"流".

数据的传输好像流水一样,从一个容器到另一个容器.

程序中数据的传输也是如此.

7.3.1 Python的流对象

Python隐藏了流机制, 在Python的模块中找不到类似的Stream类.

Python把文件的处理和流关联在一起,流对象实现了File类的所有方法.

sys模块提供了3种基本的流对象-- stdin stdout stderr

分别表示 标准输入 标准输出 错误输出



(1) stdin

>>> import sys

>>> sys.stdin = open("1.txt", "r")

>>> for line in sys.stdin.readlines() :

... print line

...

hello

world!

>>>

(2) stdout

>>> sys.stdout = open("1.txt", "a")

>>> print "last"

>>> sys.stdout.close()

(3) stderr

日志文件通常用于记录应用程序每次操作的执行结果.

日志文件的记录便于维护人员了解当前系统的状况,

也可以用于数据的恢复(例如数据库日志文件).

>>> import sys,time

>>> sys.stderr = open("record", "w")

>>> sys.stderr.write("error")

>>> sys.stderr.close()

>>> sys.stdin = open("record")

>>> sys.stdin.read()

'error'

7.3.2 模拟Java的输入流和输出流

7.4 文件处理示例--文件属性浏览程序

目的:

通过给点目录路径,查看文件的属性(名称,大小,创建时间,修改访问时间)

实现:

1) 递归目录

2) os模块的stat()函数返回文件属性信息
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: