一、文件的处理
1、文件的打开和创建
mode方式:
r 只读
r+ 读写
w 写入,首先将源文件清空,如果没有该文件则创建
w+读写,首先将源文件清空,如果没有该文件则创建,可以写入输出
a 写入,在文件末尾追加新内容,如果没有该文件则创建
a+读写,在文件末尾追加新内容,如果没有该文件则创建
文件的打开:有两种方法,一个是open,一个是file
file(name,mode)
>>> file('/zhj/a','r')
<open file '/zhj/a', mode 'r' at 0x7fd5427e65d0>
>>> p=file('/zilch/a','r') 打开后用一个对象(p)来记录文件此时的打开状态,然后进行读写操作
2.文件的读取和写入
<1>.文件的读取
read( ):
>>> file('/zhj/a','r')
<open file '/zhj/a', mode 'r' at 0x7fd5427e65d0>
>>> p=file('/zhj/a','r')
>>> p.read()
'hello world\nhello china \nhello everyone\n'
readline( ):一行一行的读取,并且返回的是字符串
>>> p=file('/zhj/a','r')
>>> p.readline()
'zhanghaijuan\n'
>>> p.readline()
'hello\tworld'
readlines( ): 读取文件中所有的或剩余的内容,并且返回的是一个列表
读取所有:
>>> p=file('/zhj/a','r')
>>> p.readlines()
['zhanghaijuan\n', 'hello\tworld']
读取剩余:
>>> p=file('/zhj/a','r')
>>> p.seek(3)
>>> p.readlines()
['nghaijuan\n', 'hello\tworld']
<2>.写入
用w写入新内容:
>>> p=file('/zhj/a','w')
>>> p.write('zhanghaijuan')
>>> p.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading
由上下可知w与w+的区别,w是清空原文件并写入新内容,但是不能读取,而w+写入后能读取
用w+写入新内容:
>>> p=file('/zhj/a','w+')
>>> p.write('zhanghaijuan\nhello\tworld')
>>> p.read()
''
>>> p.seek(0)
>>> p.read()
'zhanghaijuan\nhello\tworld'
当用w+写入新内容后,读取内容,文件动态中显示了写入的新内容,交换模式下却返回空,是指针到了文件的最后,用seek(0)让指针回到文件的起始位置,这时才能读取到写入的内容
用a写入新内容:
>>> p=file('/zhj/a','a')>>> p.write('123456789987654321')
>>> p.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading
a与a+的区别,a在原文件的末尾追加新内容,不能读取,a+追加完了后能读取
用a+写入新内容:
>>> p.write('\n123456\n123456789\n6490876')
>>> str=p.read()
>>> p.seek(0)
>>> p.read()
'hello\tworld\nhello\tchina\nhello\teveryone\n123456\n123456789\n6490876'
3.文件的查找和替换:
查找a中的hello有几个
>>> import re
>>> p=file('/zhj/a','r')
>>> count=0
>>> for a in p.readlines():
... s=re.findall('hello',a)
... if len(s)>0:
... count=count+len(s)
...
>>> print count
3
将查找到的hello全部替换成hi
>>> p=file('/zhj/a','r')
>>> o=file('/zhj/b','w')
>>> for a in p.readlines():
... o.write(a.replace('hello','good'))
...
>>> p.close()
>>> o.close()
>>> o=file('/zhj/b','r')
>>> o.read()
'good\tworld\ngood\tchina\ngood\teveryone'
4.目录的操作
通过os模块来实现操作, os的功能是对进程和进程运行环境进行管理,os 模块还负责处理大部分的文件系统操作, 应用程序
<1>创建目录
mkdir(path)
makedirs(path/py/ / /)创建多层目录
<2>删除目录
rmdir(path)
removedirs(path/py/ / / )删除多层目录
<3>目录的遍历
有三种方法,一种是递归函数,一种是os.path.walk( ),一种是os.walk( )