如何從文字檔案中刪除換行符?
在本文中,我們將向您展示如何使用 Python 從給定的文字檔案中刪除換行符 (\n)。
假設我們有一個名為 TextFile.txt 的文字檔案,其中包含一些隨機文字。我們將從給定的文字檔案中刪除換行符 (\n)。
TextFile.txt
Good Morning TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome TutorialsPoint Learn with a joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
使用 open() 函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
with open(inputFile, 'r') as filedata:
使用 readlines() 函式(返回一個列表,其中檔案的每一行都表示為列表項。要限制返回的行數,請使用提示引數。如果返回的總位元組數超過指定數量,則不再返回更多行)獲取給定輸入文字檔案的所有行列表,並在末尾帶有換行符 (\n)。
file.readlines(hint)
使用 rstrip() 函式(刪除任何尾隨字元,即字串末尾的字元。要刪除的預設尾隨字元是空格)和列表推導式(這裡我們使用 for 迴圈迭代列表中的每一行),從上述文字檔案的所有行列表中刪除換行符 (\n) 並列印它們。
list comprehension: When you wish to build a new list based on the values of an existing list, list comprehension provides a shorter/concise syntax.
使用 close() 函式關閉輸入檔案(用於關閉已開啟的檔案)。
示例
以下程式逐行檢查給定單詞是否在文字檔案的一行中找到,如果找到則列印該行:
# input text file inputFile = "ExampleTextFile.txt" # Opening the given file in read-only mode with open(inputFile, 'r') as filedata: # Reading the file lines using readlines() linesList= filedata.readlines() # Removing the new line character(\n) from the list of lines print([k.rstrip('\n') for k in linesList]) # Closing the input file filedata.close()
輸出
執行上述程式將生成以下輸出:
['Good Morning TutorialsPoint', 'This is TutorialsPoint sample File', 'Consisting of Specific', 'source codes in Python, Seaborn,Scala', 'Summary and Explanation', 'Welcome TutorialsPoint', 'Learn with a joy']
我們向程式提供了一個包含一些隨機內容的文字檔案,然後以讀取模式開啟它。然後使用 readlines() 函式檢索檔案中所有行的列表。使用列表推導式,我們遍歷檔案的每一行,並使用 rstrip() 方法刪除換行符。最後,我們透過列印更新後的行(不帶換行符)關閉了檔案。
因此,從本文中,我們瞭解瞭如何開啟檔案並從中讀取行,這可用於執行諸如查詢一行中的單詞數、行的長度等操作。我們還了解了如何將列表推導式用於簡潔易懂的程式碼,以及如何從檔案的每一行刪除換行符。此方法也可用於從檔案的行中刪除任何特定字母/單詞。
廣告