목표 : 파일을 선택하여 확장자를 .txt로 변환하고 기존 확장자를 저장합니다. 그리고 .txt로 변환된 확장자를 다시 기존 확장자로 변경합니다.
목적 : 확장자가 .txt가 아닌 파일들은 문자열 작업이 힘들기 때문에 문자열 작업(추가, 수정, 삭제 등)을 쉽게하기 위해서 확장자를 .txt로 변환/재변환 하는 것을 모듈로 만들어 편하게 사용하기 위함
전체 코드입니다. 여기에 "OpenFileorFolder.Openfile_OnenextTwo" 객체가 상속되어 사용되는데 이 모듈은 "python - 폴더 선택하여 경로만 가져오기/경로 문자반환(tkinter, filedialog, askdirectory)"에서 작성된 모듈을 사용하였습니다. 사용법을 원하는 분들은 위의 글을 사용하면 됩니다. 계속해서 모듈을 확장시켜서 편하게 사용하기 위한 목적이 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import sys
from os import rename, listdir
import os
from pathlib import Path
import OpenFileorFolder
class ChangeTextandRestoreOnT(OpenFileorFolder.Openfile_OnenextTwo):
def __init__(self, nameSavedpath = "default_text.txt", fileExtension=r"*.*"):
super().__init__(nameSavedpath, fileExtension)
def set_data(self, file_path_name):
self.file_path = file_path_name[:file_path_name.rfind('/')]
self.file_list = listdir(self.file_path)
self.file_name = file_path_name[file_path_name.rfind('/')+1:]
self.file_path_and_name = file_path_name
self.file_origin_extension = file_path_name[file_path_name.rfind('.'):]
self.file_changed_path_and_namd = ""
return self.file_path, self.file_list, self.file_name
def change_textfile(self):
self.set_data(self.findFile())
self.file_changed_path_and_namd = self.file_path_and_name.replace(self.file_origin_extension, '.txt')
os.rename(self.file_path_and_name, self.file_changed_path_and_namd)
print("{} 확장자에서 txt확장자로 변경!".format(self.file_origin_extension))
def change_text_to_original(self):
os.rename(self.file_changed_path_and_namd, self.file_path_and_name)
print("기존 확장자로 변경!")
def change_txt2x_restore_x2txt(self, func_input):
self.change_textfile()
func_input()
self.change_text_to_original()
|
cs |
1. 코드 설명
설명이 위, 코드가 아래
1) class선언
라인1 - OpenFileorFolder.Openfile_OnenextTwo class를 상속한다. OpenFileorFolder.py 파일 내 Openfile_OnenextTwo class를 사용하겠다는 의미입니다. 사용하는 이유는 Tkinter를 이용하여 파일을 선택하여 해당 경로/파일명칭/확장자명칭 까지 문자열을 return하여 가져오는 작업이 구현되어있는 class를 사용하는 것 입니다.
라인2, 3 - 상속class의 매서드를 사용하기 위해 class 초기화
1
2
3
|
class ChangeTextandRestoreOnT(OpenFileorFolder.Openfile_OnenextTwo):
def __init__(self, nameSavedpath = "default_text.txt", fileExtension=r"*.*"):
super().__init__(nameSavedpath, fileExtension)
|
cs |
2) setter 매서드
라인1 - setter 매서드 선언하고 file path name을 받아서 인스턴스 변수에 저장하는 함수
라인2~7 - 인스턴스 변수명과 동일하게 데이터를 문자열을 나눠서 file path, file list, file name, file path and name 등 과 동일하게 데이터를 저장해준다.
라인 9 - file path, list, name을 return해준다.(받을 사람은 받으라는 이야기)
1
2
3
4
5
6
7
8
9
|
def set_data(self, file_path_name):
self.file_path = file_path_name[:file_path_name.rfind('/')]
self.file_list = listdir(self.file_path)
self.file_name = file_path_name[file_path_name.rfind('/')+1:]
self.file_path_and_name = file_path_name
self.file_origin_extension = file_path_name[file_path_name.rfind('.'):]
self.file_changed_path_and_namd = ""
return self.file_path, self.file_list, self.file_name
|
cs |
3) 확장자 txt_file 변경 매서드
라인2 - 2)에서 정의한 set_data 매서드에 file_path_name을 넣어줘야 하는데 상속받은 Openfile_OnenextTwo 내에 존재하는 메서드인 findFile함수(tKinter를 사용하여 원하는 파일 선택 후 파일경로/파일이름(확장자포함) 의 문자열을 return)를 사용하여 인스턴스 변수들을 모두 업데이트한다.
라인3 - self.file_changed_path_and_namd인스턴스 변수에는 변경될 파일경로/파일명칭에 확장자만 .txt로 변경된 값을 저장한다.
라인4 - os 내 rename을 통해 파일 확장자명을 변경한다. rename(현재 경로내 파일/확장자, 변경될 경로내 파일/확장자) 를 통해 진행한다. 여기선 2) setter에서 저장한 현재 파일경로/파일명과 라인3에서 저장한 self.file_changed_path_and_namd 변수를 통하여 확장자 변경을 완료한다.
라인5 - 확장자가 변경되었음을 알리는 print를 넣었다.
1
2
3
4
5
|
def change_textfile(self):
self.set_data(self.findFile())
self.file_changed_path_and_namd = self.file_path_and_name.replace(self.file_origin_extension, '.txt')
os.rename(self.file_path_and_name, self.file_changed_path_and_namd)
print("{} 확장자에서 txt확장자로 변경!".format(self.file_origin_extension))
|
cs |
4) 기존 확장자로 다시 변경을 위한 매서드
단순하게 rename의 입력값을 반대로 넣으면 끝이난다. 여기에 쓰기 위해서 인스턴스 변수에 파일 경로/파일명을 모두 저장한 것이다.
1
2
3
|
def change_text_to_original(self):
os.rename(self.file_changed_path_and_namd, self.file_path_and_name)
print("기존 확장자로 변경!")
|
cs |
5) .txt변경 후 다시 기존 확장자를 변경해주면서 중간에 함수를 실행해주는 매서드
이 매서드를 정의한 이유는 일일이 change_textfile, change_text_to_original 매서드를 실행해주지 않고 중간에 무언가 작업을 한 뒤에 자동으로 기존 확장자로 변경을 해줄 수 있도록 설계한 것이다.
라인2 에 change_textfile, 라인 4에 change_text_to_original 를 넣고 사이에 함수 입력을 넣도록 설계한 것이다,
1
2
3
4
|
def change_txt2x_restore_x2txt(self, func_input):
self.change_textfile()
func_input()
self.change_text_to_original()
|
cs |
2. 실제 사용
라인 3 - ChangeTextfileandRestore.py 모듈을 만들었고 위에서 정의한 class ChangeTextandRestoreOnT 를 사용하기 위하여 import 하였습니다.
라인 5, 6 - ChangeTextandRestoreOnT 내 myFilenamechange.change_txt2x_restore_x2txt(test_func) 매서드에 들어갈 임의의 함수를 정의하였습니다. 중간에 실행되는 것을 확인하기 위해서 print도 하였습니다.
라인 8 - 객체 생성
라인 9 - txt 파일 변경 후 기존 확장자로 다시 돌리는 매서드 실행!
1
2
3
4
5
6
7
8
9
|
import os
import ChangeTextfileandRestore
def test_func():
print("넣고 싶은 함수를 넣으면 됩니다.")
myFilenamechange = ChangeTextfileandRestore.ChangeTextandRestoreOnT("Change_text_r01.txt")
myFilenamechange.change_txt2x_restore_x2txt(test_func)
|
cs |
실행결과
1) change_textfile 매서드 진입하면 .txt 확장자변경 print실행
2) test_func중간에 실행하여 print실행
3) change_text_to_original 매서드 진입하면서 다시 기존 확장자 변경하고 print실행

끝.
댓글