最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python讀寫txt文本文件的操作方法全解析

 更新時(shí)間:2016年06月26日 17:18:20   作者:pmghong  
這篇文章主要介紹了Python讀寫txt文本文件的操作方法全解析,包括對(duì)文本的查找和替換等技巧的講解,需要的朋友可以參考下

一、文件的打開和創(chuàng)建

>>> f = open('/tmp/test.txt')
>>> f.read()
'hello python!\nhello world!\n'
>>> f
<open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>

 
二、文件的讀取
步驟:打開 -- 讀取 -- 關(guān)閉

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


讀取數(shù)據(jù)是后期數(shù)據(jù)處理的必要步驟。.txt是廣泛使用的數(shù)據(jù)文件格式。一些.csv, .xlsx等文件可以轉(zhuǎn)換為.txt 文件進(jìn)行讀取。我常使用的是Python自帶的I/O接口,將數(shù)據(jù)讀取進(jìn)來存放在list中,然后再用numpy科學(xué)計(jì)算包將list的數(shù)據(jù)轉(zhuǎn)換為array格式,從而可以像MATLAB一樣進(jìn)行科學(xué)計(jì)算。

下面是一段常用的讀取txt文件代碼,可以用在大多數(shù)的txt文件讀取中

filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt文件和當(dāng)前腳本在同一目錄下,所以不用寫具體路徑
pos = []
Efield = []
with open(filename, 'r') as file_to_read:
  while True:
    lines = file_to_read.readline() # 整行讀取數(shù)據(jù)
    if not lines:
      break
      pass
     p_tmp, E_tmp = [float(i) for i in lines.split()] # 將整行數(shù)據(jù)分割處理,如果分割符是空格,括號(hào)里就不用傳入?yún)?shù),如果是逗號(hào), 則傳入‘,'字符。
     pos.append(p_tmp)  # 添加新讀取的數(shù)據(jù)
     Efield.append(E_tmp)
     pass
   pos = np.array(pos) # 將數(shù)據(jù)從list類型轉(zhuǎn)換為array類型。
   Efield = np.array(Efield)
   pass

例如下面是將要讀入的txt文件

2016626171647895.png (429×301)

經(jīng)過讀取后,在Enthought Canopy的variable window查看讀入的數(shù)據(jù), 左側(cè)為pos,右側(cè)為Efield。

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

三、文件寫入(慎重,小心別清空原本的文件)
步驟:打開 -- 寫入 -- (保存)關(guān)閉
直接的寫入數(shù)據(jù)是不行的,因?yàn)槟J(rèn)打開的是'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>

 應(yīng)該先指定可寫的模式

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

但此時(shí)數(shù)據(jù)只寫到了緩存中,并未保存到文件,而且從下面的輸出可以看到,原先里面的配置被清空了

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

關(guān)閉這個(gè)文件即可將緩存中的數(shù)據(jù)寫入到文件中

>>> f1.close()
[root@node1 ~]# cat /tmp/test.txt
[root@node1 ~]# hello boy!

注意:這一步需要相當(dāng)慎重,因?yàn)槿绻庉嫷奈募嬖诘脑?,這一步操作會(huì)先清空這個(gè)文件再重新寫入。那么如果不要清空文件再寫入該如何做呢?
使用r+ 模式不會(huì)先清空,但是會(huì)替換掉原先的文件,如下面的例子: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!

如何實(shí)現(xiàn)不替換?

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

可以看到,如果在寫之前先讀取一下文件,再進(jìn)行寫入,則寫入的數(shù)據(jù)會(huì)添加到文件末尾而不會(huì)替換掉原先的文件。這是因?yàn)橹羔樢鸬?,r+ 模式的指針默認(rèn)是在文件的開頭,如果直接寫入,則會(huì)覆蓋源文件,通過read() 讀取文件后,指針會(huì)移到文件的末尾,再寫入數(shù)據(jù)就不會(huì)有問題了。這里也可以使用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!

關(guān)于其他模式的介紹,見下表:

2016626170852899.png (713×317)

文件對(duì)象的方法:
f.readline()   逐行讀取數(shù)據(jù)
方法一:

>>> 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()   將文件內(nèi)容以列表的形式存放

>>> f = open('/tmp/test.txt')
>>> f.readlines()
['hello girl!\n', 'hello boy!\n', 'hello man!']
>>> f.close()

f.next()   逐行讀取數(shù)據(jù),和f.readline() 相似,唯一不同的是,f.readline() 讀取到最后如果沒有數(shù)據(jù)會(huì)返回空,而f.next() 沒讀取到數(shù)據(jù)則會(huì)報(bào)錯(cuò)

>>> 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(偏移量,選項(xiàng))

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

這個(gè)例子可以充分的解釋前面使用r+這個(gè)模式的時(shí)候,為什么需要執(zhí)行f.read()之后才能正常插入
f.seek(偏移量,選項(xiàng))
(1)選項(xiàng)=0,表示將文件指針指向從文件頭部到“偏移量”字節(jié)處
(2)選項(xiàng)=1,表示將文件指針指向從文件的當(dāng)前位置,向后移動(dòng)“偏移量”字節(jié)
(3)選項(xiàng)=2,表示將文件指針指向從文件的尾部,向前移動(dòng)“偏移量”字節(jié)

偏移量:正數(shù)表示向右偏移,負(fù)數(shù)表示向左偏移

>>> 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()    將修改寫入到文件中(無需關(guān)閉文件)

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

四、內(nèi)容查找和替換
1、內(nèi)容查找
實(shí)例:統(tǒng)計(jì)文件中hello個(gè)數(shù)
思路:打開文件,遍歷文件內(nèi)容,通過正則表達(dá)式匹配關(guān)鍵字,統(tǒng)計(jì)匹配個(gè)數(shù)。

[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、替換
實(shí)例:把test.txt 中的hello全部換為"hi",并把結(jié)果保存到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!

實(shí)例:讀取文件test.txt內(nèi)容,去除空行和注釋行后,以行為單位進(jìn)行排序,并將結(jié)果輸出為result.txt。test.txt 的內(nèi)容如下所示:

#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():                # 逐行讀取數(shù)據(jù)
line = line.strip()                #去掉每行頭尾空白
if not len(line) or line.startswith('#'):   # 判斷是否是空行或注釋行
continue                  #是的話,跳過不處理
result.append(line)              #保存
result.sort()                       #排序結(jié)果
print result
open('cdays-4-result.txt','w').write('%s' % '\n'.join(result))        #保存入結(jié)果文件

相關(guān)文章

  • Python實(shí)現(xiàn)樹的先序、中序、后序排序算法示例

    Python實(shí)現(xiàn)樹的先序、中序、后序排序算法示例

    這篇文章主要介紹了Python實(shí)現(xiàn)樹的先序、中序、后序排序算法,結(jié)合具體實(shí)例形式分析了Python數(shù)據(jù)結(jié)構(gòu)中樹的定義及常用遍歷、排序操作技巧,需要的朋友可以參考下
    2017-06-06
  • Python?中如何將十六進(jìn)制轉(zhuǎn)換為?Base64

    Python?中如何將十六進(jìn)制轉(zhuǎn)換為?Base64

    本篇文章將介紹在?Python?中將?hex?轉(zhuǎn)換為?base64?的方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • 一文詳解Python中l(wèi)ogging模塊的用法

    一文詳解Python中l(wèi)ogging模塊的用法

    logging是Python標(biāo)準(zhǔn)庫中記錄常用的記錄日志庫,主要用于輸出運(yùn)行日志,可以設(shè)置輸出日志的等級(jí)、日志保存路徑、日志文件回滾等。本文主要來和大家聊聊它的具體用法,希望對(duì)大家有所幫助
    2023-02-02
  • 使用wxPython和OpenCV實(shí)現(xiàn)手勢(shì)識(shí)別相機(jī)功能

    使用wxPython和OpenCV實(shí)現(xiàn)手勢(shì)識(shí)別相機(jī)功能

    在這篇博客中,我將分享一個(gè)有趣的?Python?項(xiàng)目:通過?wxPython?創(chuàng)建圖形界面,利用?OpenCV?的計(jì)算機(jī)視覺技術(shù)實(shí)現(xiàn)實(shí)時(shí)手勢(shì)識(shí)別,以下是項(xiàng)目的完整實(shí)現(xiàn)過程,包括代碼分析、使用說明和可能的優(yōu)化建議,需要的朋友可以參考下
    2025-04-04
  • Python如何利用%操作符格式化字符串詳解

    Python如何利用%操作符格式化字符串詳解

    %是Python風(fēng)格的字符串格式化操作符,非常類似C語言里的printf()函數(shù)的字符串格式化,下面這篇文章主要給大家介紹了關(guān)于Python如何利用%操作符格式化字符串的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • 將Python代碼嵌入C++程序進(jìn)行編寫的實(shí)例

    將Python代碼嵌入C++程序進(jìn)行編寫的實(shí)例

    這篇文章主要介紹了將Python代碼嵌入C++程序進(jìn)行編寫的實(shí)例,盡管通常還是Python代碼中調(diào)用C++程序的情況較多...需要的朋友可以參考下
    2015-07-07
  • Python通過fnmatch模塊實(shí)現(xiàn)文件名匹配

    Python通過fnmatch模塊實(shí)現(xiàn)文件名匹配

    這篇文章主要介紹了Python通過fnmatch模塊實(shí)現(xiàn)文件名匹配,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-09-09
  • Python Tkinter GUI編程入門介紹

    Python Tkinter GUI編程入門介紹

    這篇文章主要介紹了Python Tkinter GUI編程入門介紹,本文講解了Tkinter介紹、Tkinter的使用、Tkinter的幾何管理器等內(nèi)容,并給出了一個(gè)完整示例,需要的朋友可以參考下
    2015-03-03
  • Python計(jì)算元素在列表中出現(xiàn)的次數(shù)實(shí)例

    Python計(jì)算元素在列表中出現(xiàn)的次數(shù)實(shí)例

    本文介紹如何在Python中定義一個(gè)列表,并使用count()方法計(jì)算某個(gè)元素在列表中出現(xiàn)的次數(shù),示例中展示了具體的操作步驟和輸出結(jié)果
    2024-11-11
  • tensorflow TFRecords文件的生成和讀取的方法

    tensorflow TFRecords文件的生成和讀取的方法

    本篇文章主要介紹了tensorflow TFRecords文件的生成和讀取的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02

最新評(píng)論

安图县| 莱阳市| 邻水| 志丹县| 客服| 石景山区| 辽宁省| 龙口市| 桦甸市| 客服| 米脂县| 安溪县| 额尔古纳市| 翁牛特旗| 根河市| 措美县| 滨海县| 五家渠市| 淳化县| 双鸭山市| 洱源县| 西贡区| 贞丰县| 桐庐县| 商丘市| 大埔县| 同江市| 乌拉特中旗| 页游| 吉水县| 贵阳市| 西乡县| 大化| 永兴县| 崇信县| 克山县| 兴安盟| 轮台县| 长岭县| 仲巴县| 鄱阳县|