:: python
python :: 파이썬 텍스트 파일 내 특정 단어 치환(replace)하기
토람이
2021. 6. 23. 23:44
파일 내 특정 단어를 다른 단어로 치환할 때 파이썬에서는 replace 를 사용한다.
def replace_in_file(file_path, old_str, new_str):
# 파일 읽어들이기
fr = open(file_path, 'r')
lines = fr.readlines()
fr.close()
# old_str -> new_str 치환
fw = open(file_path, 'w')
for line in lines:
fw.write(line.replace(old_str, new_str))
fw.close()
# 호출: file1.txt 파일에서 comma(,) 없애기
replace_in_file("C:\\test\\file1.txt", ",", "")
** 'r'(read) 모드로 파일을 읽어들인 후 'w'(write) 모드로 치환한 내용을 쓰게 했다.
(읽으면서 동시에 쓰려고 하면 에러가 난다.)
참고로, 파이썬 replace 는 바꿀 횟수를 지정할 수 있다.
line.replace(old_str, new_str, 1) # 바꿀 횟수 1로 지정
위 경우는 line을 앞에서부터 읽다가 처음 나타나는 old_str 한 번만 치환하고 다음으로 넘어간다.
바꿀 횟수를 따로 지정하지 않으면 line 내의 모든 old_str 에 대해 치환한다.
(java 의 replaceAll 과 같은 기능)
만약 line을 뒤에서부터 읽어서 치환하려면 음수(-)로 지정하면 된다.
line.replace(old_str, new_str, -2) # 뒤에서부터 읽어들이면서 old_str 두 개까지 치환
300x250