【发布时间】:2013-10-18 14:40:03
【问题描述】:
我对 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,那么 string 与 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,它会给出以下错误,
Traceback(最近一次调用最后一次):
文件“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,而第二个在没有编码的情况下运行。
【问题讨论】:
标签: python string python-3.x