一、文件的打开和创建

>>> f = open('/tmp/test.txt')
>>> f.read()
'hello python!\nhello world!\n'
>>> f
<open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>

二、文件的读取

步骤:打开 -- 读取 -- 关闭

>>> f = open('/tmp/test.txt')
>>> f.read()
'hello python!\nhello world!\n'
>>> f.close()

三、文件写入(慎重,小心别清空原本的文件)

步骤:打开 -- 写入 -- (保存)关闭

直接的写入数据是不行的,因为默认打开的是'r' 只读模式

>>> f.write('hello boy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing
>>> f
<open file '/tmp/test.txt', mode 'r' at 0x7fe550a49d20>

应该先指定可写的模式

>>> f1 = open('/tmp/test.txt','w')
>>> f1.write('hello boy!')

但此时数据只写到了缓存中,并未保存到文件,而且从下面的输出可以看到,原先里面的配置被清空了

[root@node1 ~]# cat /tmp/test.txt
[root@node1 ~]#

关闭这个文件即可将缓存中的数据写入到文件中

>>> f1.close()
[root@node1 ~]# cat /tmp/test.txt
[root@node1 ~]# hello boy!
注意:这一步需要相当慎重,因为如果编辑的文件存在的话,这一步操作会先清空这个文件再重新写入。那么如果不要清空文件再写入该如何做呢?
使用r+ 模式不会先清空,但是会替换掉原先的文件,如下面的例子:hello boy! 被替换成hello aay!
>>> f2 = open('/tmp/test.txt','r+')
>>> f2.write('\nhello aa!')
>>> f2.close()
[root@node1 python]# cat /tmp/test.txt
hello aay!

如何实现不替换?

>>> f2 = open('/tmp/test.txt','r+')
>>> f2.read()
'hello girl!'
>>> f2.write('\nhello boy!')
>>> f2.close()
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!

可以看到,如果在写之前先读取一下文件,再进行写入,则写入的数据会添加到文件末尾而不会替换掉原先的文件。这是因为指针引起的,r+ 模式的指针默认是在文件的开头,如果直接写入,则会覆盖源文件,通过read() 读取文件后,指针会移到文件的末尾,再写入数据就不会有问题了。这里也可以使用a 模式

>>> f = open('/tmp/test.txt','a')
>>> f.write('\nhello man!')
>>> f.close()
>>>
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!
hello man!

关于其他模式的介绍,见下表:

模式

描述

r

以读方式打开文件,可读取文件信息。

w

以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容

a

以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建

r+

以读写方式打开文件,可对文件进行读和写操作。

w+

消除文件内容,然后以读写方式打开文件。

a+

以读写方式打开文件,并把文件指针移到文件尾。

b

以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。

文件对象的方法:
f.readline()   逐行读取数据
方法一:
>>> f = open('/tmp/test.txt')
>>> f.readline()
'hello girl!\n'
>>> f.readline()
'hello boy!\n'
>>> f.readline()
'hello man!'
>>> f.readline()
''

方法二:

>>> for i in open('/tmp/test.txt'):
...     print i
...
hello girl!
hello boy!
hello man!

f.readlines()     将文件内容以列表的形式存放

>>> f = open('/tmp/test.txt')
>>> f.readlines()
['hello girl!\n', 'hello boy!\n', 'hello man!']
>>> f.close()

f.next()   逐行读取数据,和f.readline() 相似,唯一不同的是,f.readline() 读取到最后如果没有数据会返回空,而f.next() 没读取到数据则会报错

>>> f = open('/tmp/test.txt')
>>> f.readlines()
['hello girl!\n', 'hello boy!\n', 'hello man!']
>>> f.close()
>>>
>>> f = open('/tmp/test.txt')
>>> f.next()
'hello girl!\n'
>>> f.next()
'hello boy!\n'
>>> f.next()
'hello man!'
>>> f.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

f.writelines()   多行写入

>>> l = ['\nhello dear!','\nhello son!','\nhello baby!\n']
>>> f = open('/tmp/test.txt','a')
>>> f.writelines(l)
>>> f.close()
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!
hello man!
hello dear!
hello son!
hello baby!

f.seek(偏移量,选项)

>>> f = open('/tmp/test.txt','r+')
>>> f.readline()
'hello girl!\n'
>>> f.readline()
'hello boy!\n'
>>> f.readline()
'hello man!\n'
>>> f.readline()
' '
>>> f.close()
>>> f = open('/tmp/test.txt','r+')
>>> f.read()
'hello girl!\nhello boy!\nhello man!\n'
>>> f.readline()
''
>>> f.close()
这个例子可以充分的解释前面使用r+这个模式的时候,为什么需要执行f.read()之后才能正常插入
f.seek(偏移量,选项)

选项=0,表示将文件指针指向从文件头部到“偏移量”字节处

选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节

选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节

偏移量:正数表示向右偏移,负数表示向左偏移
>>> f = open('/tmp/test.txt','r+')
>>> f.seek(0,2)
>>> f.readline()
''
>>> f.seek(0,0)
>>> f.readline()
'hello girl!\n'
>>> f.readline()
'hello boy!\n'
>>> f.readline()
'hello man!\n'
>>> f.readline()
''

f.flush()    将修改写入到文件中(无需关闭文件)

>>> f.write('hello python!')
>>> f.flush()
[root@node1 python]# cat /tmp/test.txt
hello girl!
hello boy!
hello man!
hello python!

f.tell()   获取指针位置

>>> f = open('/tmp/test.txt')
>>> f.readline()
'hello girl!\n'
>>> f.tell()
12
>>> f.readline()
'hello boy!\n'
>>> f.tell()
23

四、内容查找和替换

一、内容查找

实例:统计文件中hello个数

思路:打开文件,遍历文件内容,通过正则表达式匹配关键字,统计匹配个数。

[root@node1 ~]# cat /tmp/test.txt
hello girl!
hello boy!
hello man!
hello python!
脚本如下:
方法一:
#!/usr/bin/python
import re
f = open('/tmp/test.txt')
source = f.read()
f.close()
r = r'hello'
s = len(re.findall(r,source))
print s
[root@node1 python]# python count.py
4

方法二:

#!/usr/bin/python
import re
fp = file("/tmp/test.txt",'r')
count = 0
for s in fp.readlines():
li = re.findall("hello",s)
if len(li)>0:
count = count + len(li)
print "Search",count, "hello"
fp.close()
[root@node1 python]# python count1.py
Search 4 hello
二、替换
实例:把test.txt 中的hello全部换为"hi",并把结果保存到myhello.txt中。
#!/usr/bin/python
import re
f1 = open('/tmp/test.txt')
f2 = open('/tmp/myhello.txt','r+')
for s in f1.readlines():
f2.write(s.replace('hello','hi'))
f1.close()
f2.close()
[root@node1 python]# touch /tmp/myhello.txt
[root@node1 ~]# cat /tmp/myhello.txt
hi girl!
hi boy!
hi man!
hi python!

实例:读取文件test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为result.txt。test.txt 的内容如下所示:

#some wordsSometimes in life,
You find a special friend;
Someone who changes your life just by being part of it.
Someone who makes you laugh until you can't stop;
Someone who makes you believe that there really is good in the world.
Someone who convinces you that there really is an unlocked door just waiting for you to open it.
This is Forever Friendship.
when you're down,
and the world seems dark and empty,
Your forever friend lifts you up in spirits and makes that dark and empty world
suddenly seem bright and full.
Your forever friend gets you through the hard times,the sad times,and the confused times.
If you turn and walk away,
Your forever friend follows,
If you lose you way,
Your forever friend guides you and cheers you on.
Your forever friend holds your hand and tells you that everything is going to be okay. 

脚本如下:

f = open('cdays-4-test.txt')
result = list()
for line in f.readlines():                                # 逐行读取数据
line = line.strip()                                #去掉每行头尾空白
if not len(line) or line.startswith('#'):     # 判断是否是空行或注释行
continue                                   #是的话,跳过不处理
result.append(line)                            #保存
result.sort()                                              #排序结果
print result
open('cdays-4-result.txt','w').write('%s' % '\n'.join(result))               #保存入结果文件

Python 学习笔记 (6)—— 读写文件相关推荐

  1. python敏感词过滤代码简单代码,Python学习笔记系列——读写文件以及敏感词过滤器的实现...

    一.读文件 #打开文件,传入文件名和标识符,r代表读 f= open('\\Users\ZC\Desktop\zc.txt','r') #调用read方法一次性读取文件的全部内容,存入内存,用str对 ...

  2. Python学习笔记D9(文件)

    Python学习笔记D9(文件) 文件 1.打开文件 open(file, mode='r') 接收两个参数:文件名(file)和模式(mode),用于打开一个文件,并返回文件对象,如果该文件无法被打 ...

  3. Python学习笔记九:文件I/O

    打印到屏幕: 1 #!/usr/bin/python 2 3 print "Python is really a great language,", "isn't it? ...

  4. Python学习笔记之头部文件

    首先是设置Python的运行模式 即我们常见的开头那一行#!/usr/bin/python3或者#!/usr/bin/python 主要是用来指定运行方式 与我们在终端中输入:python3 xxx. ...

  5. Python学习笔记--6.2 文件读写

    #文件中所有读到的内容都是字符串open('a.txt')#file('a.txt','w')python2里用file.3里只用open # r只读.打开的文件不存在的话,会报错.不写模式的话,默认 ...

  6. python 学习笔记(十二) 文件和序列化

    python 文件读写和序列化学习. ## python文件读写 `1 打开并且读取文件` f = open('openfile.txt','r') print(f.read()) f.close() ...

  7. 深度之眼 - Python学习笔记——第八章 文件、异常和模块

    第八章 文件.异常和模块 实际应用中,我们绝大多数的数据都是通过文件的交互完成的 8.1 文件的读写 8.1.1 文件的打开 文件的打开通用格式 with open("文件路径", ...

  8. python学习笔记之操作文件,模块使用

    文件操作: 基础操作: 创建/打开文件: #语法 file=open(filename,mode='r',buffering=-1,encoding=None,errors=None,newline= ...

  9. Python学习笔记三(文件操作、函数)

    一.文件处理 1.文件打开模式 打开文本的模式,默认添加t,需根据写入或读取编码情况添加encoding参数. r   只读模式,默认模式,文件必须存在,不能存在则报异常. w  只写模式,若文件不存 ...

  10. 【Python学习笔记】- 04 文件操作

    对文件的操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 准备一个待读取的文件 <斗破苍穹>是一本连载于起点中文网的古装玄幻小说,作者是起点白金作家天蚕土 ...

最新文章

  1. 沈航计算机复试刷人,过来人的血泪教训:复试被刷原因大盘点
  2. InfBox V7.0 企业绩效助手客户端使用简介
  3. Spring 中的各种注解,光会用可不够哦!
  4. Spring Cloud(三):Eureka控制台参数说明
  5. php和派森,安装多版本Python,一个神器足矣
  6. 【操作系统】核心知识归纳总结
  7. Hemberg-lab单细胞转录组数据分析(六)
  8. JUC编程入门(高并发)
  9. Linux CentOS 7 JDK7 Tomcat7 的配置
  10. hasp hl加密狗驱动
  11. pads2007 LISENCE 报错解决方案
  12. 会计信息系统复习资料
  13. 测试心得--快易需求文档编辑系统
  14. “硬件极客”:树莓派Raspberrypi安装Kali Linux保姆教程(通过树莓派安装ARM Kali教程)
  15. 前端面试 - 项目流程
  16. 图解密码学密钥的分配方式
  17. 如何把两个视频拼在一个画面上?这样制作“画中画”
  18. N-Tiers開發方式(ASP/ASP.NET、VB6/VB.NET呼叫使用COM+元件)
  19. linux如何把文件压缩成,linux把文件压缩成.tar.gz的命令
  20. java web应用程序开发框架

热门文章

  1. 用python计算2+4+6+…+20的值_Day4-Python-循环和分之学习-2018/7/19
  2. python 生成器_Python生成器
  3. Python让繁琐工作自动化——chapter12 处理Excel电子表格
  4. python行号不显示_python IDLE添加行号显示教程
  5. 表单修改php参数,php – 使用参数修改symfony表单的url
  6. firewalld--centos7.x的防火墙--使用流程步骤:
  7. 帆软复选框选中并打印(按某种格式打印)数据分析、报填可用
  8. 驱动程序和应用程序的区别_复仇者黑客组织—教你写第一个Linux设备驱动程序...
  9. c++ vector排序_儿童时间管理课6:便利贴时间排序法
  10. 一份神奇的礼物(1)