首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python3将'str‘(不是“字节”)连接到’TypeError‘

Python3将'str‘(不是“字节”)连接到’TypeError‘
EN

Stack Overflow用户
提问于 2020-01-03 10:43:01
回答 1查看 6.7K关注 0票数 2

我想将现有的python 2脚本迁移到python 3,下面的代码在py2中工作,但在py3中不起作用:

代码语言:javascript
运行
复制
file_path = "subfolder\a_file.bin"

with file(file_path + ".cap", "wb") as f: f.write(data)

这里所做的仅仅是取一个文件路径,并使用".cap"添加一个扩展名,该扩展名也位于该子文件夹中。

所以我对它做了如下修改:

代码语言:javascript
运行
复制
with open(os.path.abspath(file_path) + ".cap" , 'wb') as f: f.write(data)

我知道错误:

代码语言:javascript
运行
复制
TypeError: can only concatenate str (not "bytes") to str

也尝试过:with open(os.path.abspath(str(file_path)+ ".cap"))

我还试着得到这样的绝对路径:

代码语言:javascript
运行
复制
my_dictonary = {
         "subfolder\a_file.bin" :  ["A3", "B3", "2400"] ,
         "subfolder\b_file.bin" :  ["A4", "B4", "3000"] , 
}

for d in my_dictonary :
    with open(d, "rb") as r: data = r.read()

    content= ""

    for line in my_dictonary[d]:
        content= content+ str(line) + "\n"

    file_set = set()

    for filename in glob.iglob('./**/*', recursive=True):
         file_set.add(os.path.abspath(filename))

    f_slice = d.split('\\')
    f_slice = f_slice[1].split(".bin")
    file_n = ""
    for e in file_set:
        if f_slice[0] in e and ".cap" in e:
            file_n = e

with open(file_n, 'wb') as f: f.write(content + data)

我打印了file_n以确保其正确的文件路径,但即使这样也会引发上述错误。如何将这个额外的/秒文件扩展名添加到".bin"中,然后打开该文件?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-07 07:41:35

您正在使用以下内容阅读:

代码语言:javascript
运行
复制
with open(d, "rb") as r: data = r.read()

并尝试使用以下方法编写:

代码语言:javascript
运行
复制
with open(file_n, 'wb') as f: f.write(content + data)

除了这个之外,这个content + data没有问题。您正在尝试将str对象连接到byte (声明为content = ""content变量)。

下面的代码将重现相同的问题:

代码语言:javascript
运行
复制
>>> byte_like_object = b'This is byte string '
>>> type(byte_like_object)
<class 'bytes'>
>>> string_like_object = 'This is some string type '
>>> type(string_like_object)
<class 'str'>

>>> string_like_object + byte_like_object

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    string_like_object + byte_like_object
TypeError: can only concatenate str (not "bytes") to str

为了解决这个问题,您需要将encode对象encodebyte,因为您正在用'wb'写入文件。

代码语言:javascript
运行
复制
>>> string_like_object.encode('utf-8') + byte_like_object
b'This is some string type This is byte string'
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59577129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档