Python學習_從文件讀取數據和保存數據


運用Python中的內置函數open()與文件進行交互

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()方法回到文件起始位置
0
>>> 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()
View Code

 

 讀取文件后,將不同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)
            line_spoken=line_spoken.strip()
            if role=='Man':
                man.append(line_spoken)
            elif role=='Other Man':
                other.append(line_spoken)
        except ValueError:
                pass
    data.close()
except IOError:
    print('The datafile is missing!')
print (man)
print (other)

 

 Tips:

使用open()方法打開磁盤文件時,默認的訪問模式為r,表示讀,不需要特意指定;

要打開一個文件完成寫,需要指定模式w,如data=open("sketch.txt","w"),如果該文件已經存在則會清空現有內容;

要追加到一個文件,需要指定模式a,不會清空現有內容;

要打開一個文件完成寫和讀,且不清空現有內容,需要指定模式w+;

 

 例如,將上例中保存的man和other內容以文件方式保存時,可修改如下:

 1 import os
 2 print(os.getcwd())
 3 os.chdir('C:\Python33\HeadFirstPython\chapter3')
 4 man=[]
 5 other=[]
 6 
 7 try:
 8     data=open("sketch.txt")
 9     for each_line in data:
10         try:
11             (role, line_spoken)=each_line.split(':', 1)
12             line_spoken=line_spoken.strip()
13             if role=='Man':
14                 man.append(line_spoken)
15             elif role=='Other Man':
16                 other.append(line_spoken)
17         except ValueError:
18                 pass
19     data.close()
20 except IOError:
21     print('The datafile is missing!')
22 
23 try:
24     man_file=open('man.txt', 'w')      #以w模式訪問文件man.txt
25     other_file=open('other.txt','w')   #以w模式訪問文件other.txt
26     print (man, file=man_file)           #將列表man的內容寫到文件中
27     print (other, file=other_file)
28 except IOError:
29     print ('File error')
30 finally:
31     man_file.close()
32     other_file.close()

但是第26行print()為什么會報錯?“syntax error while detecting tuple”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM