如何在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