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

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

文件对象的方法:

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 "", line 1, in 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)) #保存入结果文件

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

相关文章

相关视频

网友评论

文明上网理性发言,请遵守 新闻评论服务协议我要评论

立即提交

专题推荐独孤九贱-php全栈开发教程

全栈 100W+

主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门

玉女心经-web前端开发教程

入门 50W+

主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门

天龙八部-实战开发教程

实战 80W+

主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习

php中文网:公益在线php培训,帮助PHP学习者快速成长!

Copyright 2014-2020 https://www.php.cn/ All Rights Reserved | 苏ICP备2020058653号-1

python教程文件 txt_Python读写txt文本文件的操作方法全解析相关推荐

  1. python读取txt文件写入-Python读写txt文本文件的操作方法全解析

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

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

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

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

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

  4. python txt文件 报文分析_Python读写txt文本文件的操作方法全解析

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

  5. python读文本文件的过程是怎样的_读写文本文件的步骤_Python读写txt文本文件的操作方法全解析...

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

  6. pythontxt文件操作_Python读写txt文本文件的操作方法全解析

    一.文件的打开和创建 ? 1 2 3 4 5 >>> f= open('/tmp/test.txt') >>> f.read() 'hello python!\nh ...

  7. python不同数据的读入_python读写不同编码txt文件_python读写txt文件

    python读写不同编码txt文件_python读写txt文件 以后整理规范 [python] view plaincopy import os import codecs filenames=os. ...

  8. 用python修改文件内容修改txt内容的3种方法

    用python修改文件内容修改txt内容的3种方法 方法一.修改原文件方式 def updateFile(file,old_str,new_str):"""替换文件中的字 ...

  9. unity webgl读写txt文件_VB 读写txt文件

    No.7 读写txt文件​mp.weixin.qq.com 许多程序需要读写数据,比如商品管理,图书管理,学生档案等,当需要查询的时候,就是读取数据,新增或者更改就需要写数据,VB来讲,中小型的数据一 ...

最新文章

  1. php怎么做签到系统,PHP如何实现签到功能
  2. ELK+logback搭建日志系统
  3. 压缩可以卸载吗_番禺街坊注意!微信发送高清大文件不压缩,网友:QQ可以卸载了?...
  4. Hadoop! | 大数据百科 | 数据观 | 中国大数据产业观察_大数据门户
  5. [转]形态学操作:膨胀与腐蚀
  6. LoadRunner调用Oracle存储过程
  7. qq围棋 android,腾讯围棋(QQ围棋)
  8. java v3格式转换wav格式比特率是13kbps_java 压缩mp3 比特率
  9. 原来在Android中请求权限也可以有这么棒的用户体验(转自郭霖)
  10. 不拆无损,在北汽EU5,EU7,EX3,EX7安装app应用
  11. 字符串—解压缩(C语言)
  12. 磁带机PowerVault LTO-7使用
  13. Linux系统 运行小花仙游戏(针对2021年Flash停止维护的情况)
  14. 通达信接口公式怎样进行破解?
  15. 解决vscode c++ 无法跳转代码(区别于大部分网上的解决方案)
  16. 御用导航官方网站提醒提示页_砼讯 | 河海大学官方网站全新改版上线!
  17. 数据仓库中的ETL,到底是什么
  18. 解决Win10磁盘活动时间100%,读取速度为0的最终方案
  19. ZOJ3944 People Counting ZOJ3939 The Lucky Week (模拟)
  20. 《Presto(Trino)——The Definitive Guide》Presto指南20版

热门文章

  1. 携程运维自动化平台,上万服务器变更也可以很轻松
  2. 鸿蒙轻内核源码分析:虚拟文件系统 VFS
  3. Apache Log4j2远程代码执行漏洞攻击,华为云安全支持检测拦截
  4. 零信任能力成熟度模型白皮书发布!内附下载资源
  5. 云图说 | 华为云医疗智能体,智联大健康,AI药物研发
  6. 【智简联接,万物互联】华为云·云享专家董昕:Serverless和微服务下, IoT的变革蓄势待发
  7. “3+3”看华为云FusionInsight如何引领“数据新基建”持续发展
  8. 【华为云技术分享】漫谈LiteOS-Huawei_IoT_Link_SDK_OTA 开发指导
  9. 怎么在HTML上显示数据库的表格,在预定义的html表格中显示数据库表格记录
  10. android studio moudel,Android Studio将module变为library