如何使用 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.
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP