读写文本文件的步骤解析.docx

上传人:b****3 文档编号:24817978 上传时间:2023-06-01 格式:DOCX 页数:12 大小:17.79KB
下载 相关 举报
读写文本文件的步骤解析.docx_第1页
第1页 / 共12页
读写文本文件的步骤解析.docx_第2页
第2页 / 共12页
读写文本文件的步骤解析.docx_第3页
第3页 / 共12页
读写文本文件的步骤解析.docx_第4页
第4页 / 共12页
读写文本文件的步骤解析.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

读写文本文件的步骤解析.docx

《读写文本文件的步骤解析.docx》由会员分享,可在线阅读,更多相关《读写文本文件的步骤解析.docx(12页珍藏版)》请在冰豆网上搜索。

读写文本文件的步骤解析.docx

读写文本文件的步骤解析

读写文本文件的步骤解析

读写文本文件的步骤_Python读写txt文本文件的操作方法全解析

一、文件的打开和创建

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

f.read()

'hellopython!

helloworld!

'

f

二、文件的读取

步骤:

打开--读取--关闭

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

f.read()

'hellopython!

helloworld!

'

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=[]

withopen(filename,'r')asfile_to_read:

whileTrue:

lines=file_to_read.readline()#整行读取数据

ifnotlines:

break

pass

p_tmp,E_tmp=[float(i)foriinlines.split()]#将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号,则传入‘,'字符。

pos.append(p_tmp)#添加新读取的数据

Efield.append(E_tmp)

pass

pos=np.array(pos)#将数据从list类型转换为array类型。

Efield=np.array(Efield)

pass

例如下面是将要读入的txt文件经过读取后,在EnthoughtCanopy的variablewindow查看读入的数据,左侧为pos,右侧为Efield。

步骤:

打开--写入--(保存)关闭

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

f.write('helloboy')

Traceback(mostrecentcalllast):

File"",line1,in

IOError:

Filenotopenforwriting

f

应该先指定可写的模式

f1=open('/tmp/test.txt','w')

f1.write('helloboy!

')

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

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

[root@node1~]#

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

f1.close()

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

[root@node1~]#helloboy!

注意:

这一步需要相当慎重,因为如果编辑的文件存在的话,这一步操作会先清空这个文件再重新写入。

那么如果不要清空文件再写入该如何做呢?

使用r+模式不会先清空,但是会替换掉原先的文件,如下面的例子:

helloboy!

被替换成helloaay!

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

f2.write('helloaa!

')

f2.close()

[root@node1python]#cat/tmp/test.txt

helloaay!

如何实现不替换?

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

f2.read()'hellogirl!

'

f2.write('helloboy!

')

f2.close()

[root@node1python]#cat/tmp/test.txt

hellogirl!

helloboy!

可以看到,如果在写之前先读取一下文件,再进行写入,则写入的数据会添加到文件末尾而不会替换掉原先的文件。

这是因为指针引起的,r+模式的指针默认是在文件的开头,如果直接写入,则会覆盖源文件,通过read()读取文件后,指针会移到文件的末尾,再写入数据就不会有问题了。

这里也可以使用a模式

f=open('/tmp/test.txt','a')

f.write('helloman!

')

f.close()

[root@node1python]#cat/tmp/test.txt

hellogirl!

helloboy!

helloman!

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

文件对象的方法:

f.readline()逐行读取数据

方法一:

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

f.readline()

'hellogirl!

'

f.readline()

'helloboy!

'

f.readline()

'helloman!

'

f.readline()

''

方法二:

foriinopen('/tmp/test.txt'):

...printi

...

hellogirl!

helloboy!

helloman!

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

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

f.readlines()

['hellogirl!

','helloboy!

','helloman!

']

f.close()

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

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

f.readlines()

['hellogirl!

','helloboy!

','helloman!

']

f.close()

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

f.next()

'hellogirl!

'

f.next()

'helloboy!

'

f.next()

'helloman!

'

f.next()

Traceback(mostrecentcalllast):

File"",line1,in

StopIteration

f.writelines()多行写入

l=['hellodear!

','helloson!

','hellobaby!

']

f=open('/tmp/test.txt','a')

f.writelines(l)

f.close()

[root@node1python]#cat/tmp/test.txt

hellogirl!

helloboy!

helloman!

hellodear!

helloson!

hellobaby!

f.seek(偏移量,选项)

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

f.readline()

'hellogirl!

'

f.readline()

'helloboy!

'

f.readline()

'helloman!

'

f.readline()

''

f.close()

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

f.read()

'hellogirl!

helloboy!

helloman!

'

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

'hellogirl!

'

f.readline()

'helloboy!

'

f.readline()

'helloman!

'

f.readline()

''

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

f.write('hellopython!

')

f.flush()

[root@node1python]#cat/tmp/test.txt

hellogirl!

helloboy!

helloman!

hellopython!

f.tell()获取指针位置

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

f.readline()

'hellogirl!

'

f.tell()

12

f.readline()

'helloboy!

'

f.tell()

23

四、内容查找和替换

1、内容查找

实例:

统计文件中hello个数

思路:

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

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

hellogirl!

helloboy!

helloman!

hellopython!

脚本如下:

方法一:

#!

/usr/bin/python

importre

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

source=f.read()

f.close()

r=r'hello'

s=len(re.findall(r,source))

prints

[root@node1python]#pythoncount.py

4

方法二:

#!

/usr/bin/python

importre

fp=file("/tmp/test.txt",'r')

count=0

forsinfp.readlines():

li=re.findall("hello",s)

iflen(li)0:

count=count+len(li)

print"Search",count,"hello"

fp.close()

[root@node1python]#pythoncount1.py

Search4hello

2、替换

实例:

把test.txt中的hello全部换为"hi",并把结果保存到myhello.txt中。

#!

/usr/bin/python

importre

f1=open('/tmp/test.txt')

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

forsinf1.readlines():

f2.write(s.replace('hello','hi'))

f1.close()

f2.close()

[root@node1python]#touch/tmp/myhello.txt

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

higirl!

hiboy!

himan!

hipython!

实例:

读取文件test.txt内容,去除空行和注释行后,以行为进行排序,并将结果输出为result.txt。

test.txt的内容如下所示:

#somewords

Sometimesinlife,

Youfindaspecialfriend;

Someonewhochangesyourlifejustbybeingpartofit.

Someonewhomakesyoulaughuntilyoucan'tstop;

Someonewhomakesyoubelievethattherereallyisgoodintheworld.

Someonewhoconvincesyouthattherereallyisanunlockeddoorjustwaitingforyoutoopenit.

ThisisForeverFriendship.

whenyou'redown,

andtheworldseemsdarkandempty,

Yourforeverfriendliftsyouupinspiritsandmakesthatdarkandemptyworld

suddenlyseembrightandfull.

Yourforeverfriendgetsyouthroughthehardtimes,thesadtimes,andtheconfusedtimes.

Ifyouturnandwalkaway,

Yourforeverfriendfollows,

Ifyouloseyouway,

Yourforeverfriendguidesyouandcheersyouon.

Yourforeverfriendholdsyourhandandtellsyouthateverythingisgoingtobeokay.

如下:

f=open('cdays-4-test.txt')

result=list()

forlineinf.readlines():

#逐行读取数据

line=line.strip()#去掉每行头尾空白

ifnotlen(line)orline.startswith('#'):

#判断是否是空行或注释行

continue#是的话,跳过不处理

result.append(line)#保存

result.sort()#排序结果

printresult

open('cdays-4-result.txt','w').write('%s'%''.join(result))#保存入结果文件

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 医药卫生 > 临床医学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1