如何使用Python將文字檔案讀入列表或陣列?


Python內建了檔案建立、寫入和讀取功能。在Python中,可以處理兩種型別的檔案:文字檔案和二進位制檔案(以二進位制語言、0和1編寫)。有6種訪問檔案的方式。

要讀取文字檔案,我們使用只讀('r')模式開啟文字檔案進行讀取。控制代碼位於文件的開頭。

有幾種方法可以使用python將文字檔案讀入列表或陣列

使用open()方法

open()函式從開啟的檔案建立一個檔案物件。檔名和模式引數傳遞給open()函式。

示例

以下是一個示例,其中使用open()函式以只讀模式開啟檔案。現在可以使用read()函式讀取檔案。然後,使用print()函式列印檔案資料。

#Python program to read a text file into a list
#opening a file in read mode using open()
file = open('example.txt', 'r')

#read text file into list
data = file.read()
#printing the data of the file
print(data)

輸出

執行上述程式後,將生成以下輸出。

Coding encourages you to use logic and algorithms to create a program.
When facing a new challenge, you need to follow a logical approach to solve the issue.
Therefore, this is an exercise for your brain to train up your logical ability. 

邏輯思維不僅關乎解決演算法,也對您的個人和職業生活大有裨益。

使用numpy中的load()方法

在Python中,numpy.load()用於從文字檔案載入資料,目標是快速讀取簡單的文字檔案。檔名和模式引數傳遞給open()函式。

示例1

在以下示例中,從numpy模組匯入loadtxt,並將文字檔案讀入numpy陣列。使用print()函式將資料列印到列表中。

from numpy import loadtxt

#read text file into NumPy array
data = loadtxt('example.txt')
#printing the data into the list
print(data)
print(data.dtype)

輸出

執行上述程式後,將生成以下輸出。

[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14.]
Float64

loadtxt()允許我們在匯入文字檔案時選擇資料型別,這是loadtxt()的一個好特性。讓我們使用整數指定要匯入到NumPy陣列的文字檔案。

示例2

在以下示例中,從numpy模組匯入loadtxt。使用loadtxt()函式將文字檔案讀入numpy陣列。然後,使用print()函式將資料列印到列表中。

from numpy import loadtxt
#read text file into NumPy array
data = loadtxt('example.txt', dtype='int')
#printing the data into the list
print(data)
print(data.dtype)

輸出

執行上述程式後,將生成以下輸出。

[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14]
int32

使用data.replace()方法

使用Pandas建立的資料框。在資料框中,replace()函式用於替換字串、正則表示式、列表、字典、序列、數字等。由於其各種變體,這是一個非常豐富的函式。

示例

在以下示例中,檔案以讀取模式開啟,並使用read()函式讀取。行尾'\n'被替換為' ',如果進一步看到'。',則文字被分割。現在使用print()函式將資料列印為輸出。

#program to read a text file into a list
#opening the file in read mode
file = open("example.txt", "r")
data = file.read()
# replacing end of line('/n') with ' ' and
# splitting the text it further when '.' is seen.
list = data.replace('\n', '').split(".")

# printing the data
print(list)
file.close()

輸出

執行上述程式後,將生成以下輸出。

[' Coding encourages you to use logic and algorithms 
to create a program', 'When facing a new challenge, you need to follow a logical 
approach to solve the issue', 'Therefore, this is an exercise for your brain to 
train up your logical ability', ' Logical thinking is not only about solving 
algorithms but also beneficial to your personal and professional life', '']

更新於:2023年5月11日

13K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.