Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm và thay thế trong text file bằng Python

Code sau thực hiện replace trong text file, ghi kết quả ra file mới.

Ví dụ

f1 = open('foo.txt', 'r')
f2 = open('bar.txt', 'w')

for line in f1:
    print(line)
    f2.write(line.replace('Poetry', 'Prose'))

f1.close()
f2.close()

# Verify
f2 = open('bar.txt', 'r')
for line in f2:
    print(line, end='')
f2.close()

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.

Cách hiện đại (Python 3)

with open('foo.txt', 'r', encoding='utf-8') as f1, \
     open('bar.txt', 'w', encoding='utf-8') as f2:
    for line in f1:
        f2.write(line.replace('Poetry', 'Prose'))

Lưu ý: Dùng with để tự động close file. str.replace() thay thế tất cả occurrence.