Python の文字列と混同していますが、
このコードを考えてみましょう。
fo = open("test.txt", "wb")
fo.write(bytes('Sufiyan','UTF-8'))
このコードを実行すると、このエラーが発生します。
Traceback (most recent call last): File "C:\Users\Sufiyan\Desktop\AES\a.py", line 2, in <module> fo.write('Sufiyan') TypeError: 'str' does not support the buffer interface
bytes
したがって、それをエンコード タイプに変換して提供する必要があります。
fo = open("test.txt", "wb")
fo.write(bytes('Sufiyan','UTF-8'))
Python3x を使用する場合、文字列は Python 2.x の場合と同じ型ではないため、これは機能します。バイトにキャストする (エンコードする) 必要があります。
さて、このコードを使用してファイルに書き込むと、
def BB_cf(file, *args, **kwargs): #Create files
try:
fo = open(file)
fo.close()
except IOError:
print (file, 'not Found')
print ("Creating file.....")
fo = open(file, "w")
print (file,"Created Successfully!")
if file == 'input_Data.txt':
print(file,"is Empty..\nWriting Data..")
text = kwargs.get('text', None)
fo.write(text)
print("'"+text+"'", "is written in",file)
fo.close()
fo.close()
.
BB_cf('input_Data.txt', text='Sufiyan Ghori')
最後の 4 行目でわかるように、fo.write(text)
エンコードはしていませんが、コードはまだ機能しています。
エンコードせずにコードが機能するのはなぜですか?
にキャストするとbytes
、次のエラーが発生します。
トレースバック (最新の呼び出しが最後):
ファイル「C:\Users\Sufiyan\Desktop\AES\BlackBox.py」の 47 行目
BB_cf('input_Data.txt', text='Sufiyan Ghori') File
「C:\Users\Sufiyan\Desktop\AES\BlackBox.py」、41 行目、BB_cf
fo.write(bytes(text,'UTF-8')) TypeError: must be str, not bytes
上記のコードは両方とも Python3x を使用して実行されています。最初のコードはコード化する必要string
がBytes
あり、2 番目のコードはエンコードせずに実行されています。