Python3x中的字符串和Python2.x中的字符串不同,但它仍然在工作

2024-10-01 09:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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与python2.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')

正如您在最后第四行fo.write(text)中看到的,我还没有对它进行编码,但是代码仍然在工作。你知道吗

为什么代码在没有编码的情况下工作?你知道吗

现在如果我把它转换成bytes,它会给出以下错误

回溯(最近一次呼叫):

File "C:\Users\Sufiyan\Desktop\AES\BlackBox.py", line 47, in

BB_cf('input_Data.txt', text='Sufiyan Ghori')   File 

"C:\Users\Sufiyan\Desktop\AES\BlackBox.py", line 41, in BB_cf

fo.write(bytes(text,'UTF-8')) TypeError: must be str, not bytes

上面两个代码都是用Python3x运行的, 第一个要我把string编码成Bytes,而第二个没有编码。你知道吗


Tags: 代码textintxt编码databytesopen
1条回答
网友
1楼 · 发布于 2024-10-01 09:15:43

第一次,通过执行fo = open("test.txt", "wb")打开文件。第二次是fo = open(file, "w")。字符串"wb"向Python表示您只想使用字节而不是字符串写入文件,而第二个示例中的字符串"w"则相反。你知道吗

具体来说,open函数的文档说明:

As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

(我强调)

相关问题 更多 >