Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python을 사용하여 텍스트 파일 내에서 찾고 바꾸는 방법은 무엇입니까?


다음 코드는 주어진 텍스트 파일에서 교체를 수행합니다.

교체 후 텍스트는 새 텍스트 파일 '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.