2017-05-20 7 views
0

기존 텍스트 파일을 인코딩하여 utf-8에 쓰려고합니다. 사용자가 인코딩 할 텍스트 파일을 묻는 메뉴를 만들었지 만 그 이후에는 절대적으로 손실되었습니다. 이전 게시물을보고 있었고 코드를 코드에 통합했지만 작동 방식이나 수행 방식을 잘 모릅니다.기존 텍스트 파일을 별도의 파일로 utf-8로 인코딩하는 방법은 무엇입니까?

도움이 될 것입니다. 이 인코딩되지 이후에는 정기적으로 open 문을 사용하고 utf-8로 인코딩 된 텍스트를 바이너리로 파일을 열고 작성하지 왜

import codecs 

def getMenuSelection(): 
    print "\n" 
    print "\t\tWhich of the following files would you like to encode?" 
    print "\n" 
    print "\t\t================================================" 
    print "\t\t1. hamletQuote.txt" 
    print "\t\t2. RandomQuote.txt" 
    print "\t\t3. WeWillRockYou.txt"  
    print "\t\t================================================" 
    print "\t\tq or Q to quit" 
    print "\t\t================================================" 

    print "" 

    selection = raw_input("\t\t") 
    return selection 

again = True 

while (again == True): 

    choice = getMenuSelection() 

    if choice.lower() == 1 : 

     with codecs.open(hamletQuote.txt,'r',encoding='utf8') as f: 
      text = f.read() 

     with codecs.open(hamletQuote.txt,'w',encoding='utf8') as f: 
      f.write(text) 

    if choice.lower() == 2 : 

     with codecs.open(RandomQuote.txt,'r',encoding='utf8') as f: 
      text = f.read() 

     with codecs.open(RandomQuote.txt,'w',encoding='utf8') as f: 
      f.write(text) 

    if choice.lower() == 3 : 

     with codecs.open(WeWillRockYou.txt,'r',encoding='utf8') as f: 
      text = f.read() 

     with codecs.open(WeWillRockYou.txt,'w',encoding='utf8') as f: 
      f.write(text) 

    elif choice.lower() == "q": 
     again = False 

답변

0

, 당신은 정기적으로 읽기 모드로 파일을 열어야합니다 :

with open("hamletQuote.txt", 'r') as read_file: 
    text = read_file.read() 

with open("hamletQuote.txt", 'wb') as write_file: 
    write_file.write(text.encode("utf-8")) 

하지만 codecs를 사용하여 주장하는 경우, 당신은이 작업을 수행 할 수 있습니다

with codecs.open("hamletQuote.txt", 'r') as read_file: 
    text = read_file.read() 

with codecs.open("hamletQuote.txt", 'wb', encoding="utf-8") as write_file: 
    write_file.write(text.encode("utf-8")) 
1

당신은 일을해야하지만 귀하의 코드가 제대로 작동합니다 e 파일명 문자열. 입력 파일 이름도 출력 파일 이름과 동일하므로 입력 파일을 덮어 씁니다. 서로 다른 출력 파일 어떤 이름으로이 문제를 해결할 수 있습니다 codecs.open 지정된 모드에서 인코딩 된 파일을 열 때 작동 방법, 당신의 호기심 만약

with codecs.open("hamletQuote.txt",'r',encoding='utf8') as f: 
    text = f.read() 

with codecs.open("hamletQuote2.txt",'w',encoding='utf8') as f: 
    f.write(text) 

을; 이 경우 r은 읽기 모드를 의미합니다. w은 쓰기 모드를 나타냅니다. fread()write()을 포함한 몇 가지 메소드가있는 파일 객체를 나타냅니다.

with 문을 사용하면 파일을 간단하게 열 수 있습니다. 청소가 항상 사용되도록합니다. with 블록이 없으면 파일 작업을 마친 후 f.close()을 지정해야합니다.

+0

고맙습니다! 그러나 나는 새로운 인코딩 된 파일을 어디에서 찾을 수 있을지 궁금해하고 있었습니까? 이것은 어리석은 질문 일 가능성이 높지만, 나는 너무 길다. – Student

+0

새 파일은 스크립트가 실행 된 디렉터리와 동일한 디렉터리에 저장됩니다. 난 단지 당신의 입력과 출력 파일 이름이 동일하다는 것을 깨달았습니다. 따라서 스크립트를 실행할 때 hamletQuote.txt는 hamletQuote.txt라고도하는 새로운 utf8 인코딩 파일로 덮어 쓰게됩니다. 나는 나의 대답을 업데이트했다. 입력 파일을 보관하려면 출력 파일의 이름을 다르게 지정해야합니다. –

+0

는'codecs '대신'io'를 사용합니다. 파이썬 3과 호환되며 유니버설 라인 지원이 작동합니다. –