2015-11-28 389 views
5

私の大学ではPythonを使用していますが、私は現在の割り当てに固執しています。我々は2つのファイルを取って比較することになっています。私は単にファイルを開くしようとしていますので、私はそれらを使用することができますが、私はエラー"ValueError: embedded null character"open()を使用しているときに「ValueError:埋め込みヌル文字」

file1 = input("Enter the name of the first file: ") 
file1_open = open(file1) 
file1_content = file1_open.read() 

このエラーはどういう意味を得続けますか?

+0

? –

+0

先生は、プログラムを実行するときに使用するテスターファイルを追加しました。私にエラーを与えるテスターの最初のファイルは "Tests/4-test.txt" – Erica

+0

あなたはPythonを使用して動作しない文字列に埋め込まれたヌルバイトを持っているので、nullバイト/ sを削除する必要があります。あなたはどのOSを使用していますか? –

答えて

2

Python 3.5のファイルのデフォルトのエンコーディングは 'utf-8'です。

Windows用のファイルのデフォルトのエンコードは、他のものになる傾向があります。

あなたは2つのテキストファイルを開くしようとする場合は、この試みることがあります。標準ライブラリの一部の自動検出がなければならない

import locale 
locale.getdefaultlocale() 
file1 = input("Enter the name of the first file: ") 
file1_open = open(file1, encoding=locale.getdefaultlocale()[1]) 
file1_content = file1_open.read() 

を。

そうでなければ、独自に作成することがあります。

def guess_encoding(csv_file): 
    """guess the encoding of the given file""" 
    import io 
    import locale 
    with io.open(csv_file, "rb") as f: 
     data = f.read(5) 
    if data.startswith(b"\xEF\xBB\xBF"): # UTF-8 with a "BOM" 
     return "utf-8-sig" 
    elif data.startswith(b"\xFF\xFE") or data.startswith(b"\xFE\xFF"): 
     return "utf-16" 
    else: # in Windows, guessing utf-8 doesn't work, so we have to try 
     try: 
      with io.open(csv_file, encoding="utf-8") as f: 
       preview = f.read(222222) 
       return "utf-8" 
     except: 
      return locale.getdefaultlocale()[1] 

、その後

file1 = input("Enter the name of the first file: ") 
file1_open = open(file1, encoding=guess_encoding(file1)) 
file1_content = file1_open.read() 
ファイルから来ている
+0

プログラムに何かをインポートすることはできません – Erica