如何使用Python讀取文字檔案中的指定數量字元?
Python內建了檔案建立、寫入和讀取功能。在Python中,可以處理兩種型別的檔案:文字檔案和二進位制檔案(以二進位制語言,0和1編寫)。
讓我們瞭解如何在Python中開啟檔案。Python是一種優秀的通用程式語言,其標準庫中包含許多有用的檔案IO函式和模組。可以使用內建的`open()`函式開啟用於讀取或寫入的檔案物件。可以使用以下方法開啟檔案。
語法
`open()`方法的語法如下。
File = open(“txt_file_name” ,”access_mode”)
示例
以下是一個以讀取模式開啟名為example.txt檔案的示例。
file= open("example.txt", "r")
輸出
執行上述程式後,將生成以下輸出。
The file example.txt is opened in read mode.
在Python中讀取檔案
要讀取檔案的內容,可以使用`file_name.read(size)`,它讀取指定數量的資料並將其作為字串返回。`size`是一個可選的數字引數。如果省略`size`或為負數,則將讀取並返回檔案的全部內容。否則,讀取並返回的位元組數最大為`size`。如果檔案已到達末尾,則`file_name.read()`將返回空字串("")。
示例1
在下面的示例中,如果要讀取10個ASCII字元,則必須將值15作為引數傳遞。然後,使用`close()`函式關閉檔案。
file = open('example.txt', 'r') print(file.read(15)) file.close()
輸出
執行上述程式後,將生成以下輸出。
Reading is impo
使用`seek()`和`read()`
要從檔案的特定位置讀取特定數量的字元,我們可以使用`seek()`函式。Python中的`seek()`函式用於將檔案控制代碼的位置移動到特定位置。檔案控制代碼類似於游標,指示應在檔案中讀取或寫入資料的位置。
`read()`函式從檔案讀取指定數量的位元組並將其返回。預設值為1,這意味著讀取整個檔案。
示例2
以下是如何從檔案讀取字元的示例。首先,檔案以只讀模式開啟。要從檔案中的特定位置開始讀取,可以使用`seek()`函式。使用`print()`函式列印讀取的字元。然後,使用`close()`函式關閉檔案。
#python program to read characters from a file #Opening a file in read access mode file = open('example.txt', 'r') #To start reading from a specific position in a file, for say 10 #the read happens from the 10th position file.seek(10) #printing 15 characters using read() print(file.read(55)) #closing the opened file file.close()
輸出
執行上述程式後,將生成以下輸出。
important because it develops our thoughts, gives us e
廣告