如何在Python中讀取.data檔案?
在本文中,我們將學習什麼是.data檔案以及如何在python中讀取.data檔案。
什麼是.data檔案?
.data檔案用於儲存資訊/資料。
此格式的資料通常以逗號分隔值格式或製表符分隔值格式儲存。
此外,檔案可能為二進位制或文字檔案格式。在這種情況下,我們將需要找到另一種訪問方式。
在本教程中,我們將使用.csv檔案,但首先,我們必須確定檔案內容是文字還是二進位制。
識別.data檔案中的資料
.data檔案有兩種格式,檔案本身可以是文字或二進位制。
我們將不得不載入並測試它來確定它屬於哪一種。
讀取.data文字檔案
.data檔案通常是文字檔案,在Python中讀取檔案很簡單。
因為檔案處理是Python的內建功能,所以我們不需要匯入任何模組來處理它。
也就是說,以下是你在Python中開啟、讀取和寫入檔案的方法:
演算法(步驟)
以下是執行所需任務的演算法/步驟:
再次使用open()函式以寫入模式開啟.data檔案,將檔名和模式‘w’作為引數傳遞給它。如果指定的檔案不存在,則建立一個具有給定名稱的檔案並以寫入模式開啟它。
使用write()函式將一些隨機資料寫入檔案。
寫入資料後,使用close()函式關閉檔案。
使用open()函式(開啟檔案並返回檔案物件)以只讀模式開啟.data檔案,將檔名和模式‘r’作為引數傳遞給它。
使用read()函式(讀取檔案中指定數量的位元組並返回它們。預設值為-1,這意味著整個檔案)讀取檔案資料並列印它。
讀取檔案資料後,使用close()函式關閉檔案。
示例
以下程式演示如何在Python中讀取.data文字檔案:
# opening the .data file in write mode datafile = open("tutorialspoint.data", "w") # writing data into the file datafile.write("Hello Everyone this is tutorialsPoint!!!") # closing the file datafile.close() # opening the .data file in read-only mode datafile = open("tutorialspoint.data", "r") # reading the data of the file and printing it print('The content in the file is:') print(datafile.read()) # closing the file datafile.close()
輸出
The content in the file is: Hello Everyone this is tutorialsPoint!!!
讀取.data二進位制檔案
.data檔案也可能是二進位制檔案。這意味著我們必須更改訪問檔案的方法。
我們將以二進位制模式讀取和寫入檔案;在這種情況下,模式為rb,即讀取二進位制。
也就是說,以下是你在Python中開啟、讀取和寫入檔案的方法:
演算法(步驟)
以下是執行所需任務的演算法/步驟:
再次使用open()函式以二進位制寫入模式開啟.data檔案,傳遞相同的檔名和模式‘wb’作為引數。如果指定的檔案不存在,則建立一個具有給定名稱的檔案並以二進位制寫入模式開啟它。
當我們寫入二進位制檔案時,我們必須將資料從文字轉換為二進位制格式,我們可以使用encode()函式(Python中的encode()方法負責返回任何提供的文字的編碼形式。為了有效地儲存這些字串,程式碼點被轉換為一系列位元組。這被稱為編碼。Python的預設編碼是utf-8)。
使用write()函式將上述編碼後的資料寫入檔案。
寫入二進位制資料後,使用close()函式關閉檔案。
使用open()函式(開啟檔案並返回檔案物件)以二進位制讀取模式開啟.data檔案,將檔名和模式‘rb’作為引數傳遞給它。
使用read()函式(讀取檔案中指定數量的位元組並返回它們。預設值為-1,這意味著整個檔案)讀取檔案資料並列印它。
讀取二進位制資料後,使用close()函式關閉檔案。
示例
以下程式演示如何在Python中讀取.data二進位制檔案:
# opening the .data file in write-binary mode datafile = open("tutorialspoint.data", "wb") # writing data in encoded format into the file datafile.write("Hello Everyone this is tutorialspoint!!!".encode()) # closing the file datafile.close() # opening the .data file in read-binary mode datafile = open("tutorialspoint.data", "rb") # reading the data of the binary .data file and printing it print('The content in the file is:') print(datafile.read()) # closing the file datafile.close()
輸出
The content in the file is: b'Hello Everyone this is tutorialspoint!!!'
Python中的檔案操作相當容易理解,如果你想了解各種檔案訪問模式和方法,值得探索。
這兩種方法都可以工作,併為你提供獲取.data檔案內容資訊的方法。
現在我們知道它是哪種格式了,我們可以使用pandas為CSV檔案建立一個DataFrame。
結論
在本文中,我們學習了什麼是.data檔案以及.data檔案中可以儲存哪些型別的資料。使用open()和read()函式,我們學習瞭如何讀取幾種型別的.data檔案,例如文字檔案和二進位制檔案。我們還學習瞭如何使用encode()函式將字串轉換為位元組。