기존 텍스트 파일을 인코딩하여 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
고맙습니다! 그러나 나는 새로운 인코딩 된 파일을 어디에서 찾을 수 있을지 궁금해하고 있었습니까? 이것은 어리석은 질문 일 가능성이 높지만, 나는 너무 길다. – Student
새 파일은 스크립트가 실행 된 디렉터리와 동일한 디렉터리에 저장됩니다. 난 단지 당신의 입력과 출력 파일 이름이 동일하다는 것을 깨달았습니다. 따라서 스크립트를 실행할 때 hamletQuote.txt는 hamletQuote.txt라고도하는 새로운 utf8 인코딩 파일로 덮어 쓰게됩니다. 나는 나의 대답을 업데이트했다. 입력 파일을 보관하려면 출력 파일의 이름을 다르게 지정해야합니다. –
는'codecs '대신'io'를 사용합니다. 파이썬 3과 호환되며 유니버설 라인 지원이 작동합니다. –