2017-12-04 26 views
0

私のような特殊文字を含むTXTファイルを読み込むしようとしています: الحمدللهربالعالمينはどのようにPythonで特殊文字を含むテキストファイルを読み取る

私が使用している:

import fileinput 
fileToSearch = "test_encoding.txt" 
with open(fileToSearch, 'r', encoding='utf-8') as file: 
    counter = 0; 
    for line in file: 
     print(line) 

しかし、Pythonのクラッシュを

Traceback (most recent call last): 
    File "test.py", line 9, in <module> 
    print(line) 
    File "C:\Users\atheelm\AppData\Local\Programs\Python\Python35- 
32\lib\encodings\cp1252.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1: 
character maps to <undefined> 

私はPython 3.5.1を持っていますが、私はWindowsを使用しています。

私は、このコマンドを実行している:

py test.py > out.txt 
+0

あなたはそれらの文字 – bendl

+0

さて、あなたのプリントがあるが含まれて何かに「エンコーディング」を変更する必要があります失敗する。 # - * - coding:utf-8 - * - をスクリプトの先頭に追加することで修正できます。 UTF-8はafarsをサポートしています。このスレッドの詳細:https://stackoverflow.com/questions/39528462/python-3-print-function-with-farsi-arabic-characters – BoboDarph

+0

編集を参照してください。出力をファイルに印刷してください。まだクラッシュする –

答えて

0

使用2差分ファイルとIOを使用します。

lines=["Init"] 
with io.open(fileToSearch,'r',encoding='utf-8') as file: 
    counter = 1; 
    for line in file: 
     lines.insert(counter,str(line)) 
     counter = counter+1 
with io.open(out_file,'w',encoding='utf-8') as file: 
    for item in lines: 
     file.write("%s\n" % item) 
+0

あなた自身で解決策を見つけて良かったです。無関係なヒント:組み込み関数 'enumerate'を見てください。これは、あなたが' counter'をインクリメントすることから解放します:あなたは単純に 'for counter、line in enumerate(file):'を書くだけです。 – lenz

+0

そして、ここで 'io'モジュールは必要ありません。 Python 3では、 'io.open'はビルトイン' open'と同じです。 – lenz

+0

素敵なdidntはこの列挙について知っている ありがとう –

関連する問題