Python

[converter] docx 파일을 txt로 바꾸기

Jueun Park 2021. 1. 14. 18:50

Python 프로그램

docx -> txt

사용하기 전 pip을 이용해서 docx2txt을 설치해줘야함

pip install docx2txt

{convert.py}

import os
import docx2txt 

def docx_to_txt(path, filename):
    text = docx2txt.process(path + filename).split('\n') 
    # docx 파일의 내용이 text에 담기는데 '\n' 줄바꿈 문자 기준으로 나뉘어 리스트로 만들어 진다.
    newfile = os.path.splitext(filename)[0] + '.txt'
    f = open(path + newfile, 'w')    # txt 파일 오픈(없으면 생성됨)
    for item in text:    # text에 담긴 [[Example01], [Hello], [Hi] ...]의 요소 하나가 txt파일에 한줄로 써지게 됨.
        f.write(item + '\n')                                
    f.close()
    os.remove(path + filename)        # {file].docx는 사용이 모두 끝났으므로 삭제
    return (newfile)                        # {file}.txt가 리턴됨

인자 :
path -> 바꿀 file의 위치
ex: file/
filename -> 프로그램 이름(확장자 포함)
ex: subject.docx

영어 퀴즈프로그램의 일부로 작성했기 때문에 다른 기능과 섞여 있는데,
convert만 필요한거라면 더 효육적으로 작성할 수 있을 것 같다.
예를 들어 파일이름 필요없이, 해당 폴더 안에 있는 모든 docx 파일을 txt 파일로 바꿔줄 수도 있을 것 같다.


관련 게시글

Bash program - Convert srt to txt