如何使用 Python 將文字檔案中的奇數行復制到另一個檔案
在本文中,我們將向您展示如何使用 Python 將文字檔案中的奇數行復制到另一個文字檔案。
假設我們有一個名為 TextFile.txt 的文字檔案,其中包含一些隨機文字。我們需要將文字檔案中的所有奇數行復制到另一個檔案並打印出來。
TextFile.txt
Good Morning This is the Tutorials Point sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome everyone Learn with a joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
使用 open() 函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
readFile = open(inputFile, "r")
建立一個變數來儲存輸出檔案路徑,該路徑僅包含給定輸入檔案中的奇數行。
使用 open() 函式(開啟檔案並返回檔案物件作為結果)以寫入模式開啟輸出檔案,將檔名和模式作為引數傳遞給它(此處“w”表示寫入模式)。
使用 readlines() 函式(返回一個列表,其中檔案中的每一行都表示為列表項。要限制返回的行數,請使用 hint 引數。如果返回的位元組總數超過指定數量,則不再返回行)獲取給定輸入文字檔案的行列表。
file.readlines(hint)
使用 for 迴圈遍歷讀取文字檔案的每一行,直到檔案的長度。使用 len() 函式(len() 方法返回物件中的專案數)計算讀取檔案的長度。
使用 if 條件語句確定讀取檔案行的索引是否為奇數。
如果條件為真,則使用 write() 函式(將指定的文字寫入檔案。提供的文字將根據檔案模式和流位置插入)將讀取的檔案行寫入輸出檔案。
列印給定輸入檔案中的奇數行。
使用 close() 函式(用於關閉已開啟的檔案)關閉寫入檔案(輸出檔案)。
使用 close() 函式(用於關閉已開啟的檔案)關閉讀取檔案(輸入檔案)。
示例
以下程式將文字檔案中的奇數行復制到另一個文字檔案並列印結果奇數行:
# input text file inputFile = "ExampleTextFile.txt" # Opening the given file in read-only mode. readFile = open(inputFile, "r") # output text file path outputFile = "PrintOddLines.txt" # Opening the output file in write mode. writeFile = open(outputFile, "w") # Read the above read file lines using readlines() ReadFileLines = readFile.readlines() # Traverse in each line of the read text file for excelLineIndex in range(0, len(ReadFileLines)): # Checking whether the line number i.e excelLineIndex is even or odd # Here modulus 2 i.e %2 gives 1 for odd number and 0 for even number if(excelLineIndex % 2 != 0): # If the index is odd, then x`write the read file line into the # output file writeFile.write(ReadFileLines[excelLineIndex]) # printing the odd line print(ReadFileLines[excelLineIndex]) # Closing the write file writeFile.close() # Closing the read file readFile.close()
輸出
執行上述程式將生成以下輸出:
This is the Tutorials Point sample File source codes in Python, Seaborn,Scala Welcome everyone
我們向程式提供了一個包含一些隨機內容的文字檔案,然後以讀取模式開啟它。然後使用 readlines() 函式檢索檔案中所有行的列表,並將其儲存在一個變數中。我們遍歷檔案,直到到達所有行的總數,並檢查行號是奇數還是偶數。如果是奇數行,我們將其追加到一個新檔案中並打印出來。
結論
到目前為止,我們已經學習瞭如何開啟檔案、讀取其行以及透過索引遍歷其行,這可以用於獲取諸如第 n 個索引行或 Excel 表格中的第 n 行的值等資訊。此外,我們討論瞭如何透過索引檢索行的值並將該資料寫入檔案。