Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Find and Replace ใน Text File ด้วย Python

โค้ดต่อไปนี้ทำ Replacement ใน Text File ที่กำหนด หลัง Replace เขียนไปยังไฟล์ใหม่ 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, end='')

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.

แนะนำ: ใช้ with open(...) as f: เพื่อปิดไฟล์อัตโนมัติ