2021년 6월 20일 일요일

python에서 여러번 실행(?) 해서 폴더의 모든 파일의 문자열을 바꾸기


하려고 하는것을 말로 설명하기가 너무 힘드네요


이번에 해야할 일을 예를 들어 설명하겠습니다.

당신에게 주어진 일은 파일의 특정 text를 다른 text로 전부 변환하는 작업입니다.

파일이 있는 곳은 특정 폴더일 수도 있고 특정 폴더 하위일 수도 있습니다. 해당 파일은 모든 파일이 대상이 됩니다.

이제 감이 오시나요?


21-6-20 일요일 아침 8:25분

커피 한잔을 가지고 Bottom UP 방식으로 구현해보겠습니다.


텍스트의 변환

python string은 replace라는 훌륭한 도구가 있습니다.

replace(old, new, [count]) -> replace("찾을값", "바꿀값", [바꿀횟수])

 

파일의 읽기

f = open("파일.txt", 'r') data = f.read() f.close()


파일 쓰기

f = open("foo.txt", 'w') f.write("text") f.close()


파일 하나를 읽어서 텍스트 변환 후 저장하기

파일을 읽고 문자열을 replace로 변환 후 write 함수로 쓰면 끝납니다.

여기서 주의할점은 encoding 형식인데요, 한글이 포함된다면 'utf-8' 로 해주세요

def one_open_replace_save(infile,outfile,find_str,replace_str,encoding=None):
	fp = open(infile, 'r', encoding=encoding)
	data = fp.read()
	fp.close()
	
	instr = str(data)
	
	instr = instr.replace(find_str,replace_str)
	
	fp = open(outfile, 'w', encoding=encoding)
	fp.write(instr)
	fp.close()
	
if __name__ == "__main__":
	one_open_replace_save("9_mul_sub_txt_replace_test_in.txt","out.txt","Hello","Hi",encoding='utf-8')


폴더 탐색하기

이제 남은건 폴더안에 있는 파일들의 정보를 가져오는 방법입니다.

os 패키지나 glob 를 사용하는 방법입니다.



import glob, os
os.chdir("foldername")
for file in glob.glob("*.txt"):
    print(file)

import os
for file in os.listdir("foldername"):
    if file.endswith(".txt"):
        print(os.path.join("foldername", file))

import os
for root, dirs, files in os.walk("foldername"):
    for file in files:
        if file.endswith(".txt"):
             print(os.path.join(root, file))


완성품


import os
import sys

def one_open_replace_save(infile,outfile,find_str,replace_str,encoding="utf-8"):
	print(infile,"->",outfile)
	fp = open(infile, 'r', encoding=encoding)
	data = fp.read()
	fp.close()
	
	instr = str(data)
	
	instr = instr.replace(find_str,replace_str)
	
	fp = open(outfile, 'w', encoding=encoding)
	fp.write(instr)
	fp.close()

def visit_dir(dir_name, file_type, find_str, replace_str):
	for file in os.listdir(dir_name):
		if file.endswith("."+file_type):
			one_open_replace_save(os.path.join(dir_name, file),os.path.join(dir_name, file),find_str,replace_str)

def visit_dir_with_r(dir_name, file_type, find_str, replace_str):
	for root, dirs, files in os.walk(dir_name):
		for file in files:
			if file.endswith("."+file_type):
				one_open_replace_save(os.path.join(root, file),os.path.join(root, file),find_str,replace_str)


def visit_and_replace(dir_name, file_type, find_str, replace_str, rtype):
	if rtype==True:
		visit_dir_with_r(dir_name, file_type, find_str, replace_str)
	else:
		visit_dir(dir_name, file_type, find_str, replace_str)
	

if __name__ == "__main__":
	visit_and_replace("testfolder","txt","Hello","hi",True)

대충 위와 같은 형태가 됩니다.

마지막 인자는 재귀적으로 호출될필요가 있을때 True로 해주면 됩니다.


예제는 testfolder라는 폴더 하위에 있는 모든 txt파일을 열어서 "Hello"란 문자열이 있으면 모두 "hi"로 변경하여 저장하는 도구입니다.


Fin 9:32 1시간 좀 더 걸렸네요.


댓글 없음:

댓글 쓰기