如何使用 Python 列印檔案中包含給定字串的行?
在本文中,我們將向您展示如何使用 Python 列印給定文字檔案中包含特定給定字串的所有行。
假設我們有一個名為ExampleTextFile.txt的文字檔案,其中包含一些隨機文字。我們將從文字檔案中返回包含給定特定字串的行。
ExampleTextFile.txt
Good morning to TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome to TutorialsPoint Learn with a joy Good morning to TutorialsPoint
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
輸入字串作為靜態/動態輸入並將其儲存在變數中。
使用open()函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
with open(inputFile, 'r') as filedata:
使用for迴圈遍歷文字檔案中的每一行
使用if條件語句和“in”關鍵字檢查給定字串是否出現在上述行資料中。
in關鍵字用於確定某個值是否存在於序列(列表、範圍、字串等)中。
它也用於在for迴圈中迭代序列
如果在對應行中找到給定字串,則列印該行。
使用close()函式關閉輸入檔案(用於關閉已開啟的檔案)。
示例
以下程式逐行檢查給定字串是否在文字檔案的一行中找到,如果找到則列印該行:
# input text file inputFile = "ExampleTextFile.txt" # Enter the string givenString = "to TutorialsPoint" print('The following lines contain the string {', givenString, '}:') # Opening the given file in read-only mode with open(inputFile, 'r') as filedata: # Traverse in each line of the file for line in filedata: # Checking whether the given string is found in the line data if givenString in line: # Print the line, if the given string is found in the current line print(line) # Closing the input file filedata.close()
輸出
執行上述程式將生成以下輸出:
The following lines contain the string { to TutorialsPoint }:
Good morning to TutorialsPoint
Welcome to TutorialsPoint
Good morning to TutorialsPoint
在這個程式中,我們讀取了一個包含一些隨機文字的文字檔案。我們逐行讀取文字檔案,然後檢查給定字串是否出現在該行資料中。如果存在,則列印該行的當前值(總行值)。
結論
我們學習瞭如何讀取檔案、逐行遍歷檔案以及獲取本文中的所有行資料。一旦我們獲得它們,我們就可以反轉該行、更改大小寫、查詢該行中的單詞數、檢查母音、檢索行字元等等。我們還學習瞭如何在檔案中搜索字串並列印相關行,這在典型的日常應用程式中(例如查詢 ID 並列印所有人員資訊)中經常使用。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP