Python读写txt文本文件的操作方法全解析


Posted in Python onJune 26, 2016

一、文件的打开和创建

>>> 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()

读取数据是后期数据处理的必要步骤。.txt是广泛使用的数据文件格式。一些.csv, .xlsx等文件可以转换为.txt 文件进行读取。我常使用的是Python自带的I/O接口,将数据读取进来存放在list中,然后再用numpy科学计算包将list的数据转换为array格式,从而可以像MATLAB一样进行科学计算。

下面是一段常用的读取txt文件代码,可以用在大多数的txt文件读取中

filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt文件和当前脚本在同一目录下,所以不用写具体路径
pos = []
Efield = []
with open(filename, 'r') as file_to_read:
  while True:
    lines = file_to_read.readline() # 整行读取数据
    if not lines:
      break
      pass
     p_tmp, E_tmp = [float(i) for i in lines.split()] # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
     pos.append(p_tmp)  # 添加新读取的数据
     Efield.append(E_tmp)
     pass
   pos = np.array(pos) # 将数据从list类型转换为array类型。
   Efield = np.array(Efield)
   pass

例如下面是将要读入的txt文件

Python读写txt文本文件的操作方法全解析

经过读取后,在Enthought Canopy的variable window查看读入的数据, 左侧为pos,右侧为Efield。

Python读写txt文本文件的操作方法全解析Python读写txt文本文件的操作方法全解析

三、文件写入(慎重,小心别清空原本的文件)
步骤:打开 -- 写入 -- (保存)关闭
直接的写入数据是不行的,因为默认打开的是'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!

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

Python读写txt文本文件的操作方法全解析

文件对象的方法:
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(偏移量,选项)
(1)选项=0,表示将文件指针指向从文件头部到“偏移量”字节处
(2)选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节
(3)选项=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

四、内容查找和替换
1、内容查找
实例:统计文件中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

2、替换
实例:把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 words

Sometimes 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 相关文章推荐
Python中endswith()函数的基本使用
Apr 07 Python
python tensorflow学习之识别单张图片的实现的示例
Feb 09 Python
对Python3中的print函数以及与python2的对比分析
May 02 Python
Python地图绘制实操详解
Mar 04 Python
python zip()函数使用方法解析
Oct 31 Python
wxPython+Matplotlib绘制折线图表
Nov 19 Python
django admin 添加自定义链接方式
Mar 11 Python
关于tf.matmul() 和tf.multiply() 的区别说明
Jun 18 Python
Python pandas对excel的操作实现示例
Jul 21 Python
python实现杨辉三角的几种方法代码实例
Mar 02 Python
Django 实现jwt认证的示例
Apr 30 Python
使用Pytorch实现two-head(多输出)模型的操作
May 28 Python
Python实现快速排序算法及去重的快速排序的简单示例
Jun 26 #Python
python结合selenium获取XX省交通违章数据的实现思路及代码
Jun 26 #Python
理解生产者消费者模型及在Python编程中的运用实例
Jun 26 #Python
python安装mysql-python简明笔记(ubuntu环境)
Jun 25 #Python
Python的装饰器用法学习笔记
Jun 24 #Python
Python的网络编程库Gevent的安装及使用技巧
Jun 24 #Python
深入解析Python编程中super关键字的用法
Jun 24 #Python
You might like
php URL编码解码函数代码
2009/03/10 PHP
关于PHP二进制流 逐bit的低位在前算法(详解)
2013/06/13 PHP
ci检测是ajax还是页面post提交数据的方法
2014/11/10 PHP
php计算整个目录大小的方法
2015/06/01 PHP
php倒计时出现-0情况的解决方法
2016/07/28 PHP
浅谈PHPANALYSIS提取关键字
2019/03/08 PHP
Jquery EasyUI中弹出确认对话框以及加载效果示例代码
2014/02/13 Javascript
JS获取图片高度宽度的方法分享
2015/04/17 Javascript
Javascript实现div层渐隐效果的方法
2015/05/30 Javascript
JavaScript高级程序设计(第三版)学习笔记1~5章
2016/03/11 Javascript
JavaScript字符串对象
2017/01/14 Javascript
jQuery html表格排序插件tablesorter使用方法详解
2017/02/10 Javascript
Angular2平滑升级到Angular4的步骤详解
2017/03/29 Javascript
微信小程序MUI导航栏透明渐变功能示例(通过改变rgba的a值实现)
2019/01/24 Javascript
JS前端知识点offset,scroll,client,冒泡,事件对象的应用整理总结
2019/06/27 Javascript
微信小程序如何引用外部js,外部样式,公共页面模板
2019/07/23 Javascript
express框架中使用jwt实现验证的方法
2019/08/25 Javascript
Python中关于使用模块的基础知识
2015/05/24 Python
python如何使用正则表达式的前向、后向搜索及前向搜索否定模式详解
2017/11/08 Python
python面向对象入门教程之从代码复用开始(一)
2018/12/11 Python
详解Ubuntu16.04安装Python3.7及其pip3并切换为默认版本
2019/02/25 Python
django之自定义软删除Model的方法
2019/08/14 Python
python logging日志模块原理及操作解析
2019/10/12 Python
使用PyCharm安装pytest及requests的问题
2020/07/31 Python
美赞臣营养马来西亚旗舰店:Enfagrow马来西亚
2019/07/26 全球购物
巴西箱包、背包、钱包和旅行配件购物网站:Inovathi
2019/12/14 全球购物
农村婚礼证婚词
2014/01/08 职场文书
人事文员岗位职责
2014/02/16 职场文书
办公室打字员岗位职责
2014/04/16 职场文书
小学国庆节活动方案策划书
2014/09/16 职场文书
大学生实习证明范本
2014/09/19 职场文书
班主任寄语2015
2015/02/26 职场文书
为什么中国式养孩子很累?
2019/08/07 职场文书
Android Gradle 插件自定义Plugin实现注意事项
2022/06/16 Java/Android
Redis sentinel哨兵集群的实现步骤
2022/07/15 Redis