Python程式讀取檔案的前n行
在本文中,我們將向您展示如何使用python讀取並列印給定**N**值文字檔案的前N行。
假設我們有一個名為**ExampleTextFile.txt**的文字檔案,其中包含一些隨機文字。我們將返回給定N值文字檔案的前**N**行。
ExampleTextFile.txt
Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with a joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
輸入N值(靜態/動態)以列印檔案的前N行。
使用**open()**函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,並將檔名和模式作為引數傳遞給它(這裡“**r**”表示只讀模式)。
with open(inputFile, 'r') as filedata:
使用**readlines()**函式(返回一個列表,其中檔案中的每一行都表示為列表項。要限制返回的行數,請使用hint引數。如果返回的位元組總數超過指定數量,則不再返回行)獲取給定輸入文字檔案的行列表。
file.readlines(hint)
遍歷行列表,使用**切片**檢索文字檔案的前N行(使用切片語法,可以返回一系列字元。要返回字串的一部分,請指定起始和結束索引,用冒號分隔)。這裡linesList[:N]表示從開頭到N(不包括最後一個第N行,因為索引從0開始)的所有行。
for textline in (linesList[:N]):
逐行列印檔案的前N行。
使用**close()**函式關閉輸入檔案(用於關閉已開啟的檔案)。
示例
以下程式列印給定**N**值文字檔案的前**N**行:
# input text file inputFile = "ExampleTextFile.txt" # Enter N value N = int(input("Enter N value: ")) # Opening the given file in read-only mode with open(inputFile, 'r') as filedata: # Read the file lines using readlines() linesList= filedata.readlines() print("The following are the first",N,"lines of a text file:") # Traverse in the list of lines to retrieve the first N lines of a file for textline in (linesList[:N]): # Printing the first N lines of the file line by line. print(textline, end ='') # Closing the input file filedata.close()
輸出
執行上述程式將生成以下輸出:
Enter N value: 4 The following are the first 4 lines of a text file: Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated
我們從使用者那裡獲取了N的值(動態輸入),然後向我們的程式提供了一個包含一些隨機內容的文字檔案,並以讀取模式開啟它。然後使用readlines()函式檢索檔案中所有行的列表。我們使用for迴圈和切片遍歷了檔案的前N行並列印了它們。
結論
因此,從本文中,我們學習瞭如何開啟檔案並從中讀取行,這可以用於執行諸如查詢一行中的單詞數量、一行的長度等操作,我們還學習了切片以簡單的方式訪問開頭或結尾的元素。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP