python - Python3x 中的字符串与 Python2.x 中的字符串不同,但它仍然有效

标签 python string python-3.x

我对 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

因此,我必须将其转换为字节并提供编码类型。

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) 中看到的,我尚未对其进行编码,但代码仍然有效。

为什么代码无需编码就可以工作?

现在如果我将其转换为字节,它将给出以下错误,

回溯(最近一次调用最后一次):

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运行, 第一个要求我将字符串编码为字节,而第二个则在不编码的情况下运行。

最佳答案

第一次,您可以通过执行 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.

(重点是我添加的)

关于python - Python3x 中的字符串与 Python2.x 中的字符串不同,但它仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19452411/

相关文章:

python - Qtablewidget滚动不流畅

c - 创建动态字符串时的额外字节

java - 正则表达式帮助 - 字符串 - JWE-766.1.pdf - 模式 - Extract 766

python - 将数字保存到变量

python - Python 中的优化问题 - 如 Goal Seek

python - python3控制台和python3程序代码中的区别命令

python - 谷歌应用引擎 : Cursor Versus Offset

检查字符串是否是另一个字符串的子字符串

python-3.x - Python 使用本地 SMTP 服务器在 docker 容器内发送邮件

python - 按 "pip install --upgrade"升级 pip 和 scrapy 后出现 pip 错误