国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

從零學python系列之從文件讀取和保存數據

2020-02-23 05:24:20
字體:
來源:轉載
供稿:網友

在HeadFirstPython網站中下載所有文件,解壓后以chapter 3中的“sketch.txt”為例:

 

新建IDLE會話,首先導入os模塊,并將工作目錄卻換到包含文件“sketch.txt”的文件夾,如C://Python33//HeadFirstPython//chapter3

代碼如下:
>>> import os
>>> os.getcwd()    #查看當前工作目錄
'C://Python33'
>>> os.chdir('C:/Python33/HeadFirstPython/chapter3')   #切換包含數據文件的文件夾
>>> os.getcwd()     #查看切換后的工作目錄
'C://Python33//HeadFirstPython//chapter3'

打開文件“sketch.txt”,讀取并顯示前兩行:

代碼如下:
>>> data=open('sketch.txt')
>>> print(data.readline(),end='')
Man: Is this the right room for an argument?
>>> print(data.readline(),end='')
Other Man: I've told you once.

回到文件起始位置,使用for語句處理文件中的每行,最后關閉文件:

代碼如下:
>>> data.seek(0)   #使用seek()方法回到文件起始位置
>>> for each_line in data:
    print(each_line,end='')

   
Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
Other Man: Yes I did!
Man: You didn't!
Other Man: I'm telling you, I did!
Man: You did not!
Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
Man: Ah! (taking out his wallet and paying) Just the five minutes.
Other Man: Just the five minutes. Thank you.
Other Man: Anyway, I did.
Man: You most certainly did not!
Other Man: Now let's get one thing quite clear: I most definitely told you!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh no you didn't!
Other Man: Oh yes I did!
Man: Oh look, this isn't an argument!
(pause)
Other Man: Yes it is!
Man: No it isn't!
(pause)
Man: It's just contradiction!
Other Man: No it isn't!
Man: It IS!
Other Man: It is NOT!
Man: You just contradicted me!
Other Man: No I didn't!
Man: You DID!
Other Man: No no no!
Man: You did just then!
Other Man: Nonsense!
Man: (exasperated) Oh, this is futile!!
(pause)
Other Man: No it isn't!
Man: Yes it is!
>>> data.close()

讀取文件后,將不同role對應數據分別保存到列表man和other:

代碼如下:
import os
print(os.getcwd())
os.chdir('C:/Python33/HeadFirstPython/chapter3')
man=[]    #定義列表man接收Man的內容
other=[]  #定義列表other接收Other Man的內容

try:
    data=open("sketch.txt")
    for each_line in data:
        try:
            (role, line_spoken)=each_line.split(':', 1)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 镇江市| 土默特左旗| 镇安县| 杭锦旗| 佛冈县| 三穗县| 菏泽市| 海原县| 资源县| 拜城县| 铁力市| 湘乡市| 永平县| 延川县| 奇台县| 布尔津县| 苏尼特右旗| 新和县| 华池县| 达拉特旗| 桑日县| 满城县| 阳谷县| 涟源市| 镇赉县| 麟游县| 盱眙县| 大英县| 景宁| 靖宇县| 同德县| 余干县| 卢氏县| 永丰县| 衡阳县| 铁力市| 井冈山市| 麦盖提县| 陆良县| 武功县| 若尔盖县|