如何使用Python在一行文字檔案中寫入一行文字?
Python 內建了檔案建立、寫入和讀取功能。在 Python 中,可以處理兩種型別的檔案:文字檔案和二進位制檔案(以二進位制語言、0 和 1 編寫)。
在本文中,我們將瞭解如何向檔案中寫入內容。
首先,我們將使用 **open()** 函式以寫入模式開啟檔案。然後,**write()** 方法將使用提供的文字儲存檔案。檔案模式和流位置決定了提供的文字將被放置的位置。
**"a"** − 文字將被放置在檔案流中的當前位置,通常位於檔案的末尾。
**"w"** − 在文字插入到當前檔案流位置(預設設定為零)之前,檔案將被清空。
語法
以下是 open() 方法的語法。
file = open("file_name", "access_mode")
示例 1
讓我們來看一個以寫入模式開啟檔案的示例。如果 example.txt 檔案不存在,**open()** 函式將建立一個新檔案。
file = open('example.txt', 'w')
輸出
執行上述程式後,將生成以下輸出。
The file example.txt is opened in write mode.
示例 2
在下面的示例中,使用 **open()** 方法以寫入模式開啟一個檔案。然後,藉助 **write()** 方法將文字寫入檔案,然後使用 **close()** 方法關閉檔案。
#python program to demonstrate file write()
file = open('example.txt', 'w')
file.write( "the end")
file.close()
輸出
執行上述程式後,將生成以下輸出。
The text "the end" is written into the file. The previous contents of the file have been cleared.
在前面的示例中,我們使用寫入模式向檔案中寫入內容。為了向檔案寫入內容而不清除以前的內容,我們可以使用追加“a”模式向檔案中寫入內容。要使用追加模式向檔案寫入內容,請使用 'a' 或 'a+' 作為訪問模式開啟檔案,以將新行追加到現有檔案。以下是這些訪問模式的定義:僅追加 ('a'):開啟檔案以開始寫入。如果檔案不存在,則建立檔案。檔案控制代碼位於檔案的末尾。
示例 3
在下面的示例中,使用 open() 函式以追加模式開啟名為 example.txt 的檔案。然後,使用 write() 函式將文字寫入檔案。
#python program to demonstrate file write in append mode
file = open('example.txt', 'a')
file.write( "the end ")
輸出
執行上述程式後,將生成以下輸出。
The text is appended to the file.
示例 4
在下面的示例中,使用 **open()** 函式以追加模式開啟一個檔案。然後,使用 **write()** 函式將文字寫入檔案,並使用 **close()** 函式關閉檔案。
#python program to demonstrate file write in append mode
f = open('myfile', 'a')
f.write('hi there\n')
# python will convert \n to os.linesep
f.close()
輸出
執行上述程式後,將生成以下輸出。
The text is appended in the file in a next line.
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP