文本檔案可存盤的資料量多、每當需要分析或修改存盤在檔案中的資訊時,讀取檔案都很有用,對資料分析應用程式
處理檔案,讓程式能夠快速地分析大量的資料
處理檔案和保存資料可讓你的程式使用起來更容易
一、從檔案中讀取資料
1)讀取整個檔案:
先創建一個任意的文本檔案,設定任意行,任意個資料,命名為data.txt,如下所示:
415926535897 932384626433 832795028841 9716939 937510 234 321
打開data.txt,并讀取到程式中
with open('data.txt') as file_object: #方法open() 打開檔案 ,并且接受一個引數,即要打開的檔案的名稱 contents = file_object.read() #方法 read() 讀取這個檔案的全部內容,并將其作為字串存盤在變數 contents 中 print(contents) #列印字串contents
執行結果如下:
415926535897 932384626433 832795028841 9716939 937510 234 321
2)檔案路徑
上述 open('data.txt') 其中data.txt檔案必須和.py模塊(檔案)放在同一個檔案夾中,為方便打開其他檔案,可以使用相對檔案路徑和 絕對檔案路徑,
#使用絕對路徑打開檔案 file_path = 'E:\WorkSpace\python\coding\data.txt' #使用絕對路徑,可讀取系統任何地方的檔案 with open(file_path) as file_object: contents = file_object.read() print(contents)
3)逐行讀取
上述都是一次讀取data.txt中的內容,讀取檔案時,可能需要檢查其中的每一行或者查找特定的資訊,或者要以某種方式修改檔案中的文本,可使用 for 回圈以每次一行的方式檢查檔案,
filename = 'E:\WorkSpace\python\coding\data.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip()) #消除多余的空白
4)使用串列來存取讀入的行,其中每一行相當于串列的一個元素,(重新創建了一個pi.txt的文本,里面有若干行數字,)
pi.txt檔案內容如下:注意,前后有空格
3.14159265358979323846264338
32795028841971693993751058
20974944592307816406286208
99862803482534211706791201
611596
程式如下:
#創建一個包含檔案各行內容的串列 filename = 'pi.txt' with open(filename) as file_object: lines = file_object.readlines() #方法 readlines() 從檔案中讀取每一行,并將其存盤在一個串列中 for line in lines: # for 回圈來列印 lines 中的各行 print(line.strip()) #方法strip()去除每行首尾的空格,
5)使用檔案的內容,將檔案讀取到記憶體中后,就可以以任何方式使用這些資料,
filename = 'pi.txt' with open(filename) as file_object: lines = file_object.readlines() #方法 readlines() 從檔案中讀取每一行,并將其存盤在一個串列中 #上述代碼完成后,結果應該為:lines=['3.141592****','32795028841971','20974944592',]形式 pi_string = '' #定義一個空字串 for line in lines: # for 回圈來將lines中的各元素連接起來 pi_string += line.strip() #strip()用來消除每個元素(txt檔案中的每行)首尾的空白行 print(line.strip() ) print(pi_string) #列印連接好的字串 print(len(pi_string)) #求字串的長度
運行結果:(注意每行前后的空格已經消除,strip()方法的作用)
3.14159265358979323846264338 32795028841971693993751058 20974944592307816406286208 99862803482534211706791201 611596 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706791201611596 112
未完待續
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/460783.html
標籤:其他
上一篇:Urllib的4個模板
