一、文件的打开和创建

>>> f = open('/tmp/test.txt')

>>> f.read()

'hello python! hello world! '

>>> f

二、文件的读取步骤:打开 -- 读取 -- 关闭

>>> f = open('/tmp/test.txt')

>>> f.read()

'hello python! hello world! '

>>> 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文件

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

三、文件写入(慎重,小心别清空原本的文件)步骤:打开 -- 写入 -- (保存)关闭

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

>>> f.write('hello boy')

Traceback (most recent call last):

File "", line 1, in

IOError: File not open for writing

>>> f

应该先指定可写的模式

>>> 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(' hello aa!')

>>> f2.close()

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

hello aay!

如何实现不替换?

>>> f2 = open('/tmp/test.txt','r+')

>>> f2.read()

'hello girl!'

>>> f2.write(' hello 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(' hello man!')

>>> f.close()

>>>

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

hello girl!

hello boy!

hello man!

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

文件对象的方法:

f.readline() 逐行读取数据

方法一:

>>> f = open('/tmp/test.txt')

>>> f.readline()

'hello girl! '

>>> f.readline()

'hello boy! '

>>> 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! ', 'hello boy! ', 'hello man!']

>>> f.close()

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

>>> f = open('/tmp/test.txt')

>>> f.readlines()

['hello girl! ', 'hello boy! ', 'hello man!']

>>> f.close()

>>>

>>> f = open('/tmp/test.txt')

>>> f.next()

'hello girl! '

>>> f.next()

'hello boy! '

>>> f.next()

'hello man!'

>>> f.next()

Traceback (most recent call last):

File "", line 1, in

StopIteration

f.writelines() 多行写入

>>> l = [' hello dear!',' hello son!',' hello baby! ']

>>> 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! '

>>> f.readline()

'hello boy! '

>>> f.readline()

'hello man! '

>>> f.readline()

' '

>>> f.close()

>>> f = open('/tmp/test.txt','r+')

>>> f.read()

'hello girl! hello boy! hello man! '

>>> 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! '

>>> f.readline()

'hello boy! '

>>> f.readline()

'hello man! '

>>> 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! '

>>> f.tell()

12

>>> f.readline()

'hello boy! '

>>> 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' % ' '.join(result)) #保存入结果文件

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

本文地址: http://www.cppcns.com/jiaoben/python/154799.html

python读取txt文件写入-Python读写txt文本文件的操作方法全解析相关推荐

  1. python 打开当前目录的txt文件-Python - 读取其他文件夹/目录中的文本文件

    这是我的情况:我有一些.txt文件在我可以运行脚本的不同目录中.Python - 读取其他文件夹/目录中的文本文件 mainDir/ -face/ -57268-face-_tracker.txt - ...

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

    这篇文章主要介绍了Python读写txt文本文件的操作方法全解析,包括对文本的查找和替换等技巧的讲解,需要的朋友可以参考下 一.文件的打开和创建 ? 1 2 3 4 5 >>> f ...

  3. python读取大文件-使用Python读取大文件的方法

    背景 最近处理文本文档时(文件约2GB大小),出现memoryError错误和文件读取太慢的问题,后来找到了两种比较快Large File Reading 的方法,本文将介绍这两种读取方法. 准备工作 ...

  4. python读取.mat文件,python将变量存为.mat文件详细介绍

    在进行数据处理的过程中,经常会用到Matlab和python两种工具,.mat文件是Matlab数据存储的标准数据格式,通过创建一个.mat文件详细介绍两种工具之间的数据读取和存储. 一.python ...

  5. python读取txt文件_python实现读写txt文件的几种方法

    一.读写模式: w:向文件中写入内容,w会清空原来文本内容 a:向文件中追加内容 r:从文件中读取内容 wb:以二进制形式写入内容. rb:以二进制形式读文件内容 ab:以二进制形式追加内容 a+.r ...

  6. python读取txt文件写入-python 读取、写入txt文件的示例

    写入文件 使用open()函数和write()函数 但是有两种写法,分别是'a'和'w' 'a' 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,会接着已有的内容的后面写入 with ope ...

  7. python读取txt文件写入-python txt文件的写入和读取

    1.文件的打开 使用open () 函数 打开文件.他有两个参数,文件路径或文件名和文件的打开方式. "r" 只读模式,不能编辑和删除文件内容. "w" 写入模 ...

  8. python读取dat文件写入表格_Pandas:外部文件数据导入/ 读取 (如 :csv、txt、tsv、dat、excel文件)、文件存储(to_csv、to_excel)...

    一.文本文件读取 文本文件是一种由若干行字符构成的计算机文件,它是一种典型的顺序文件. csv是一种逗号分隔的文件格式,因为其分隔符不一定是逗号,又被称为字符分隔文件,文件以纯文本形式存储表格数据(数 ...

  9. python关闭读写的所有的文件-Python读写txt文本文件的操作方法全解析

    一.文件的打开和创建 >>> f = open('/tmp/test.txt') >>> f.read() 'hello python! hello world! ...

最新文章

  1. 网络推广策略之如何稳定新站的关键词排名?
  2. 预告 | 旷视天元的前世今生与移动端推理优化@清华专场
  3. JSONPATH使用方法
  4. C++ sort()函数的使用
  5. Android之java.lang.ClassCastException: *****cannot be cast to*******
  6. 数据挖掘流程_数据流挖掘
  7. ASP.NET (C#开发环境)Request对象 之 ServerVariables集合
  8. 新松机器人刻蚀机_中国最大机器人产业基地新松智慧园在沈阳启用
  9. 线程通信:生产者消费者问题
  10. 通过jdt解析spring mvc中url-类-方法的对应关系
  11. 【Anylogic智能体状态转移】
  12. 微信小程序防止快速点击(节流)
  13. steam无盘服务器,网吧服务器如何安装steam平台和正版游戏?
  14. js 实现简单todo效果
  15. tinyserver小型服务器
  16. linux内核编译命令 理解,谢烟客---------Linux之理解内核、内核模块、编译内核
  17. 黑客丛林通关攻略参考(更新中)
  18. 360公司开源Atlas快速上手安装配置
  19. 证明商标和普通商标的区别
  20. 涤纶电容的作用原理及优点缺点

热门文章

  1. wiredtiger存储引擎介绍——本质就是LSM,当然里面也可以包含btree和列存储
  2. springboot 应用中静态资源下载
  3. 第二十一节(数组概要, 一维、二维数组的声明和使用,数组的排序,数组的查找,)...
  4. Linux里设置环境变量的方法(转)
  5. magento 加速(.htaccess)
  6. C#调用dll中的函数
  7. 一般关于大宗商品的供需关系相关的数据网址有哪些?
  8. SpringBoot | 第九章:Mybatis-plus的集成和使用
  9. Zabbix安装 Grafana安装
  10. W5500EVB UDP模式的測试与理解