Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để tìm và thay thế trong một tệp văn bản bằng Python?


Đoạn mã sau thực hiện thay thế trong tệp văn bản đã cho.

Sau khi thay thế, văn bản được ghi vào tệp văn bản mới 'bar.txt'

Ví dụ

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()

Đầu ra

Điều này cho kết quả

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.