一、文件的打开和创建

?

12345

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

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

?

1234

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文件读取中

?

12345678910111213141516

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

2016626171647895.png (429×301)

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

2016626171713978.png (148×277)2016626171743777.png (147×280)

三、文件写入(慎重,小心别清空原本的文件)步骤:打开 -- 写入 -- (保存)关闭 直接的写入数据是不行的,因为默认打开的是'r' 只读模式

?

123456

f.write('hello boy')Traceback (most recent call last):

File "", line 1, in IOError: File not open for writing

f

应该先指定可写的模式

?

12

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

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

?

12

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

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

?

123

f1.close()

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

注意:这一步需要相当慎重,因为如果编辑的文件存在的话,这一步操作会先清空这个文件再重新写入。那么如果不要清空文件再写入该如何做呢? 使用r+ 模式不会先清空,但是会替换掉原先的文件,如下面的例子:hello boy! 被替换成hello aay!

?

12345

f2 = open('/tmp/test.txt','r+')f2.write('nhello aa!')f2.close()

[root@node1 python]# cat /tmp/test.txthello aay!

如何实现不替换?

?

12345678

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

'hello girl!'

f2.write('nhello boy!')f2.close()

[root@node1 python]# cat /tmp/test.txthello girl!hello boy!

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

?

12345678

f = open('/tmp/test.txt','a')f.write('nhello man!')f.close()

[root@node1 python]# cat /tmp/test.txthello girl!hello boy!hello man!

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

2016626170852899.png (713×317)

文件对象的方法:f.readline() 逐行读取数据 方法一:

?

123456789

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

'hello girl!n'

f.readline()

'hello boy!n'

f.readline()

'hello man!'

f.readline()

''

方法二:

?

123456789101112

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() 没读取到数据则会报错

?

12345678910111213141516

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() 多行写入

?

1234567891011

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.txthello girl!hello boy!hello man!hello dear!hello son!hello baby!

f.seek(偏移量,选项)

?

12345678910111213141516

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,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节

偏移量:正数表示向右偏移,负数表示向左偏移

?

12345678910111213

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() 将修改写入到文件中(无需关闭文件)

?

12

f.write('hello python!')f.flush()

?

1

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

?

1234

hello girl!hello boy!hello man!hello python!

f.tell() 获取指针位置

?

123456789

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

'hello girl!n'

f.tell()

12

f.readline()

'hello boy!n'

f.tell()

23

四、内容查找和替换1、内容查找实例:统计文件中hello个数 思路:打开文件,遍历文件内容,通过正则表达式匹配关键字,统计匹配个数。

?

1

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

?

1234

hello girl!hello boy!hello man!hello python!

脚本如下: 方法一:

?

12345678910

!/usr/bin/python

import ref = 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.py4

方法二:

?

123456789101112

!/usr/bin/python

import refp = file("/tmp/test.txt",'r')count = 0for 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.pySearch 4 hello

2、替换实例:把test.txt 中的hello全部换为"hi",并把结果保存到myhello.txt中。

?

1234567891011121314

!/usr/bin/python

import ref1 = 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.txthi girl!hi boy!hi man!hi python!

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

?

12345678910111213141516171819

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 worldsuddenly 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.

脚本如下:

?

12345678910

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 resultopen('cdays-4-result.txt','w').write('%s' % 'n'.join(result))

python中pos什么意思_python pos是什么相关推荐

  1. python中如何定义颜色_Python图像处理之颜色的定义与使用分析

    本文实例讲述了Python图像处理之颜色的定义与使用.分享给大家供大家参考,具体如下: python中的颜色相关的定义在matplotlib模块中,为方便使用,这里给大家展示一下在这个模块中都定义了哪 ...

  2. python中formatter的用法_Python pyplot.FuncFormatter方法代码示例

    本文整理汇总了Python中matplotlib.pyplot.FuncFormatter方法的典型用法代码示例.如果您正苦于以下问题:Python pyplot.FuncFormatter方法的具体 ...

  3. python中doc=parased.getroot()_python实例手册.py

    python实例手册 #encoding:utf8 # 设定编码-支持中文 0 说明 手册制作: 雪松 littlepy www.51reboot.com 更新日期: 2016-01-21 欢迎系统运 ...

  4. python中wx是啥_python中wx模块的具体使用方法

    wx包中的方法都是以大写字母开头的,而这和Python的习惯是相反的. 本节介绍如何创建python程序的图形用户界面(GUI),也就是那些带有按钮和文本框的窗口.这里介绍wxPython : 根据自 ...

  5. python中值滤波算法_Python实现卡尔曼滤波算法之贝叶斯滤波

    Python实现卡尔曼滤波算法之贝叶斯滤波 作者:yangjian 卡尔曼滤波器属于贝叶斯滤波器的一种特例,本文主要讲解贝叶斯滤波原理及其算法的python实现. 先来看下贝叶斯公式 贝叶斯公式 :后 ...

  6. python中的元类_python中的元类

    类也是对象,但是类有创建对象的能力 动态创建一个类: classmonkey():defbanana(self):print 'banana!' defapple(self):print 'i wan ...

  7. python中chr的用法_python中chr()函数和ord()函数的用法

    原博文 2018-06-11 21:52 − 一,chr()函数 格式:Chr(<数值表达式>) 说明:函数返回值类型为String,其数值表达式值取值范围为0~255. 例如:Print ...

  8. python中csv文件操作_python中操作csv文件

    python中操作csv文件 读取csv improt csv f = csv.reader(open("文件路径","r")) for i in f: pri ...

  9. python中for循环缩进_Python减少循环层次和缩进的技巧分析

    本文实例分析了Python减少循环层次和缩进的技巧.分享给大家供大家参考,具体如下: 我们知道Python中冒号和缩进代表大括号,这样写已经可以节省很多代码行数,但是可以更优化,尽可能减少循环的层次和 ...

  10. python中的下划线_Python中的下划线详解

    这篇文章讨论Python中下划线_的使用.跟Python中很多用法类似,下划线_的不同用法绝大部分(不全是)都是一种惯例约定. 一. 单个下划线直接做变量名(_) 主要有三种情况: 1. 解释器中 _ ...

最新文章

  1. JavaScript权威设计--CSS(简要学习笔记十六)
  2. lucene.net 应用资料
  3. cocos2d实现语音_Cocos2d-x 3.2 Lua示例CocosDenshionTest(音频测试)
  4. 更改多维数组的数据结构形式
  5. BugkuCTF-Crypto题你喜欢下棋吗
  6. ​esquisse: 快速可视化图形的 Rstudio 插件
  7. 如何查看linux中的ssh端口开启状态
  8. Git——Gitlab服务单机构建
  9. 搭建自己的下载文件服务器
  10. 古诗词学习-迢迢牵牛星+长歌行+小雅·采薇+敕勒歌+悯农(其一)+小儿垂钓+蝉+正月十五夜+望月怀远+十五夜望月寄杜郎中
  11. 物联网技能大赛-Ubuntu-(1)
  12. 易语言选单选框分组框API全选取消
  13. 程序员的三十五岁危机
  14. 珍贵数学文献(II)
  15. Linux+conda+R+Rstudio下载安装环境全方面配置
  16. 65个外贸小心思,让你稳步赢得客户
  17. 通过外部Python调用FreeCAD
  18. Go 中 Gzip 与 json 搭配使用压缩数据,减少数据传输量
  19. 【Week】No.177
  20. php跨域header处理

热门文章

  1. 将图片公式快速转为word可编辑的方法(windows和mac都支持)
  2. 阿里小蜜技术学习笔记--知识点整理
  3. matplotlib.pyplot如何绘制多张子图
  4. win7系统一键还原教程
  5. Jupyter Notebook与Pycharm代码连接Docker容器中的远程服务器运行
  6. Pre-trained Adversarial Perturbations-对抗机器学习论文
  7. echarts年龄饼图_ECharts中饼图的操作
  8. longhorn安装与使用
  9. Kubernetes存储Longhorn
  10. linux桌面lxde 安装_Ubuntu怎么安装轻量级的LXDE桌面