首页 文章

python 3.5:TypeError:写入文件时需要类似字节的对象,而不是'str'

提问于
浏览
309

我最近迁移到Py 3.5 . 这段代码在Python 2.7中正常工作:

with open(fname, 'rb') as f:
    lines = [x.strip() for x in f.readlines()]

for line in lines:
    tmp = line.strip().lower()
    if 'some-pattern' in tmp: continue
    # ... code

升级到3.5后,我得到了:

TypeError: a bytes-like object is required, not 'str'

最后一行的错误(模式搜索代码) .

我尝试在语句的任何一侧使用 .decode() 函数,也尝试过:

if tmp.find('some-pattern') != -1: continue
  • 无济于事 .

我能够迅速解决几乎所有2:3的问题,但这个小小的陈述让我烦恼 .

7 回答

  • 5

    您可以使用 .encode() 对字符串进行编码

    例:

    'Hello World'.encode()
    
  • 319

    为什么不尝试将文件作为文本打开?

    with open(fname, 'rt') as f:
        lines = [x.strip() for x in f.readlines()]
    

    另外这里是官方页面上python 3.x的链接:https://docs.python.org/3/library/io.html这是开放功能:https://docs.python.org/3/library/functions.html#open

    如果您真的想要将其作为二进制文件处理,那么请考虑编码您的字符串 .

  • 25

    就像已经提到过的那样,您正在以二进制模式读取文件,然后创建一个字节列表 . 在接下来的 for 循环中,您将比较字符串与字节,这是代码失败的地方 .

    添加到列表时解码字节应该有效 . 更改的代码应如下所示:

    with open(fname, 'rb') as f:
        lines = [x.decode('utf8').strip() for x in f.readlines()]
    

    字节类型是在Python 3中引入的,这就是为什么你的代码在Python 2中工作的原因 . 在Python 2中,没有字节的数据类型:

    >>> s=bytes('hello')
    >>> type(s)
    <type 'str'>
    
  • 76

    您以二进制模式打开文件:

    以下代码将抛出TypeError:需要类似字节的对象,而不是'str' .

    for line in lines:
        print(type(line))# <class 'bytes'>
        if 'substring' in line:
           print('success')
    

    以下代码将起作用 - 您必须使用decode()函数:

    for line in lines:
        line = line.decode()
        print(type(line))# <class 'str'>
        if 'substring' in line:
           print('success')
    
  • 10

    对于这个小例子:import socket

    mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mysock.connect(('www.py4inf.com', 80))
    mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
    
    while True:
        data = mysock.recv(512)
        if ( len(data) < 1 ) :
            break
        print (data);
    
    mysock.close()
    

    在'GET http://www.py4inf.com/code/romeo.txt HTTP / 1.0 \ n \ n'之前添加"b"解决了我的问题

  • 2

    你必须从wb改为w:

    def __init__(self):
        self.myCsv = csv.writer(open('Item.csv', 'wb')) 
        self.myCsv.writerow(['title', 'link'])
    

    def __init__(self):
        self.myCsv = csv.writer(open('Item.csv', 'w'))
        self.myCsv.writerow(['title', 'link'])
    

    更改后,错误消失,但您无法写入文件(在我的情况下) . 毕竟,我没有答案?

    资料来源:How to remove ^M

    更改为'rb'会给我带来另一个错误:io.UnsupportedOperation:write

  • 1

    您以二进制模式打开文件:

    with open(fname, 'rb') as f:
    

    这意味着从文件读取的所有数据都将作为 bytes 对象返回,而不是 str . 然后,您无法在包含测试中使用字符串:

    if 'some-pattern' in tmp: continue
    

    您必须使用 bytes 对象来测试 tmp

    if b'some-pattern' in tmp: continue
    

    或者将文件作为文本文件打开,而不是将 'rb' 模式替换为 'r' .

相关问题