使用Python將列表內容寫入檔案


在這篇文章中,我們將向您展示如何使用 Python 將列表中的資料寫入文字檔案。

假設我們已經獲取了一個列表,並將列表的所有元素寫入一個名為“ListDataFile.txt”的文字檔案,寫入後的資料如下所示。

假設我們在文字檔案中擁有以下列表:

inputList = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file']

使用此程式,我們將獲得上述字串的以下結果:

This
is
a
TutorialsPoint
sample
file

演算法(步驟)

以下是執行所需任務應遵循的演算法/步驟:

  • 建立一個變數來儲存元素列表。

  • 建立一個變數來儲存文字檔案的路徑。

  • 使用open()函式(開啟檔案並返回檔案物件作為結果)以只寫模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“w”表示寫入模式)。

with open(inputFile, 'w') as filedata:
  • 使用for迴圈遍歷輸入列表的每個元素。

  • 使用write()函式將列表的每個元素(迭代器值)寫入開啟的文字檔案(將指定的文字寫入檔案。提供的文字將根據檔案模式和流位置插入)。

  • 使用for迴圈遍歷檔案的每一行。

  • 使用close()函式關閉輸入檔案(用於關閉開啟的檔案)。

  • 使用open()函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。

with open(inputFile, 'r') as filedata:
  • 使用read()函式(從檔案中讀取指定數量的位元組並返回它們。預設值為-1,這意味著整個檔案)讀取檔案資料後,列印文字檔案的內容。

示例

下面的程式遍歷文字檔案的行,並使用collections模組中的計數器函式列印文字檔案中鍵值對的頻率:

# input list inputList = ['This', 'is', 'a', 'TutorialsPoint', 'sample', 'file'] # input text file inputFile = "ListDataFile.txt" # Opening the given file in write mode with open(inputFile, 'w') as filedata: # Traverse in each element of the input list for item in inputList: # Writing each element of the list into the file # Here “%s\n” % syntax is used to move to the next line after adding an item to the file. filedata.write("%s\n" % item) # Closing the input file filedata.close() # Opening the output text file in read-only mode fileData = open("ListDataFile.txt") # Reading the file and printing the result print(fileData.read())

輸出

執行上述程式後,將生成以下輸出:

This
is
a
TutorialsPoint
sample
file

在這個程式中,我們讀取了一個單詞列表,然後獲取一個檔案並以寫入模式開啟它。然後,使用迴圈,我們遍歷每個單詞的列表,並使用write()函式將該單詞新增到檔案中。我們使用換行符(\n)來分隔檔案的單詞。之後,我們關閉檔案並以讀取模式重新開啟它,列印檔案的所有資料(此處資料將是列表中的單詞)。

從本文中,我們學習瞭如何以寫入模式開啟檔案並向其中寫入資料,以及如何遍歷單詞列表並將這些專案複製到檔案中。如何重新開啟檔案以讀取其內容(這用於檢查單詞是否已新增到檔案中)。

更新於:2022年8月17日

3K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告