类型错误:在 Python3 中写入文件时需要类似字节的对象,而不是“str”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33054527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:41:39  来源:igfitidea点击:

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

pythonpython-3.xstringfilebyte

提问by masroore

I've very recently migrated to Py 3.5. This code was working properly in Python 2.7:

我最近迁移到 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

After upgrading to 3.5, I'm getting the:

升级到 3.5 后,我得到:

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

error on the last line (the pattern search code).

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

I've tried using the .decode()function on either side of the statement, also tried:

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

if tmp.find('some-pattern') != -1: continue

- to no avail.

——无济于事。

I was able to resolve almost all 2:3 issues quickly, but this little statement is bugging me.

我能够快速解决几乎所有的 2:3 问题,但是这个小声明让我很烦恼。

采纳答案by Martijn Pieters

You opened the file in binary mode:

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

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

This means that all data read from the file is returned as bytesobjects, not str. You cannot then use a string in a containment test:

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

if 'some-pattern' in tmp: continue

You'd have to use a bytesobject to test against tmpinstead:

您必须使用一个bytes对象来进行测试tmp

if b'some-pattern' in tmp: continue

or open the file as a textfile instead by replacing the 'rb'mode with 'r'.

或者通过将'rb'模式替换为'r'.

回答by starter

for this small example: 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()

adding the "b" before 'GET http://www.py4inf.com/code/romeo.txtHTTP/1.0\n\n' solved my problem

在“GET http://www.py4inf.com/code/romeo.txtHTTP/1.0\n\n ”之前添加“b”解决了我的问题

回答by Suresh

Like it has been already mentioned, you are reading the file in binary mode and then creating a list of bytes. In your following forloop you are comparing string to bytes and that is where the code is failing.

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

Decoding the bytes while adding to the list should work. The changed code should look as follows:

在添加到列表时解码字节应该可以工作。更改后的代码应如下所示:

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

The bytes type was introduced in Python 3 and that is why your code worked in Python 2. In Python 2 there was no data type for bytes:

字节类型是在 Python 3 中引入的,这就是您的代码在 Python 2 中工作的原因。在 Python 2 中,字节没有数据类型:

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

回答by theofpa

You can encode your string by using .encode()

您可以使用 .encode()

Example:

例子:

'Hello World'.encode()

回答by meck373

You have to change from wb to w:

您必须从 wb 更改为 w:

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

to

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

After changing this, the error disappears, but you can't write to the file (in my case). So after all, I don't have an answer?

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

Source: How to remove ^M

来源:如何删除 ^M

Changing to 'rb' brings me the other error: io.UnsupportedOperation: write

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

回答by Fernando D Jaime

why not try opening your file as text?

为什么不尝试以文本形式打开文件?

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

Additionally here is a link for python 3.x on the official page: https://docs.python.org/3/library/io.htmlAnd this is the open function: https://docs.python.org/3/library/functions.html#open

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

If you are really trying to handle it as a binary then consider encoding your string.

如果您真的想将其作为二进制文件处理,请考虑对您的字符串进行编码。

回答by Matan Hugi

You opened the file in binary mode:

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

The following code will throw a TypeError: a bytes-like object is required, not 'str'.

以下代码将抛出 TypeError:需要一个类似字节的对象,而不是“str”。

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

The following code will work - you have to use the decode() function:

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

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

回答by Shiv Buyya

Use encode() function along with hardcoded String value given in a single quote.

使用 encode() 函数以及单引号中给出的硬编码字符串值。

Ex:

前任:

file.write(answers[i] + '\n'.encode())

OR

或者

line.split(' +++$+++ '.encode())

回答by Ibrahim.H

I got this error when I was trying to convert a char (or string) to bytes, the code was something like this with Python 2.7:

当我尝试将字符(或字符串)转换为 时,出现此错误bytes,Python 2.7 的代码类似于以下内容:

# -*- coding: utf-8 -*-
print( bytes('ò') )

This is the way of Python 2.7when dealing with unicode chars.

这是Python 2.7在处理 unicode 字符时的方式。

This won't work with Python 3.6, since bytesrequire an extra argument for encoding, but this can be little tricky, since different encoding may output different result:

这不适用于 Python 3.6,因为bytes需要额外的编码参数,但这可能有点棘手,因为不同的编码可能会输出不同的结果:

print( bytes('ò', 'iso_8859_1') ) # prints: b'\xf2'
print( bytes('ò', 'utf-8') ) # prints: b'\xc3\xb2'

In my case I had to use iso_8859_1when encoding bytes in order to solve the issue.

在我的情况下,我必须iso_8859_1在编码字节时使用才能解决问题。

Hope this helps someone.

希望这可以帮助某人。