如何使用 Python 在文字檔案中查詢並替換某些內容?\n\n\n
以下程式碼在給定的文字檔案中執行替換操作。
替換後,文字將被寫入到一個新的文字檔案“bar.txt”中
示例
f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')
for line in f1:
print line
f2.write(line.replace('Poetry', 'Prose'))
f2 = open('bar.txt', 'r')
for line in f2:
print line,
f1.close()
f2.close()輸出
該程式碼的輸出為
Poetry is often considered the oldest form of literature. Poetry today is usually written down, but is still sometimes performed. Prose is often considered the oldest form of literature. Prose today is usually written down, but is still sometimes performed.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP