python 輸入,python逐行輸出_python逐行輸出

 2023-11-19 阅读 30 评论 0

摘要:一、文件的打開和創建 ? 12345 python 輸入,f = open('/tmp/test.txt')f.read()'hello python!nhello world!n'f 二、文件的讀取步驟:打開 -- 讀取 -- 關閉 ? 1234 python django?f = open('/tmp/test.txt')f.read() 'hello pyt

一、文件的打開和創建

?

12345

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

二、文件的讀取步驟:打開 -- 讀取 -- 關閉

?

1234

python django?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一樣進行科學計算。

python編程、下面是一段常用的讀取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:

python for、lines = file_to_read.readline() # 整行讀取數據

if not lines:

break

pass

python3、p_tmp, E_tmp = [float(i) for i in lines.split()] # 將整行數據分割處理,如果分割符是空格,括號里就不用傳入參數,如果是逗號, 則傳入‘,'字符。

pos.append(p_tmp) # 添加新讀取的數據

Efield.append(E_tmp)

pass

python lambda、pos = np.array(pos) # 將數據從list類型轉換為array類型。 Efield = np.array(Efield) pass

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

2016626171647895.png (429×301)

經過讀取后,在Enthought Canopy的variable window查看讀入的數據, 左側為pos,右側為Efield。

python replace、2016626171713978.png (148×277)2016626171743777.png (147×280)

三、文件寫入(慎重,小心別清空原本的文件)步驟:打開 -- 寫入 -- (保存)關閉 直接的寫入數據是不行的,因為默認打開的是'r' 只讀模式

?

123456

python結果按行輸出?f.write('hello boy')Traceback (most recent call last):

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

f

應該先指定可寫的模式

python怎么輸入兩行再執行。?

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/182795.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息