TypeError: 在 Python 3 中无法将 ‘str’(而不是 ‘bytes’)连接到 ‘bytes’。

huangapple go评论66阅读模式
英文:

Python3 concatenate 'str' (not "bytes") to 'bytes' TypeError

问题

I want to migrate an existing python 2 script to python 3 the following is working in py2 but not py3:

file_path = "subfolder\a_file.bin"

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

whats done here is just taking a file path and adding an extension with .cap which is also located in that sub folder

so I modified it like this:

with open(os.path.abspath(file_path) + ".cap" , 'wb') as f: f.write(data)

I get the error:

TypeError: can only concatenate str (not "bytes") to str

also tried: with open(os.path.abspath(str(file_path)+ ".cap"))

I also tried getting the absolute paths like this:

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)

I printed the file_n to make sure its the correct file path but even this is throwing the above error. how can add this extra/second file extension to .bin and then open that file?

英文:

I want to migrate an existing python 2 script to python 3 the following is working in py2 but not py3:

file_path = "subfolder\a_file.bin"

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

whats done here is just taking a file path and adding an extension with ".cap" which is also located in that sub folder

so I modified it like this:

with open(os.path.abspath(file_path) + ".cap" , 'wb') as f: f.write(data)

I get the error:

TypeError: can only concatenate str (not "bytes") to str

also tried: with open(os.path.abspath(str(file_path)+ ".cap"))

I also tried getting the absolute paths like this:

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)

I printed the file_n to make sure its the correct file path but even this is throwing the above error. how can add this extra/second file extension to ".bin" and then open that file?

答案1

得分: 3

只有代码部分需要翻译,以下是翻译好的内容:

你正在使用以下方式读取:

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

并尝试使用以下方式写入:

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

没有问题,除非涉及到 content + data

你正试图将 str 对象连接到 byte 上(content 变量声明如下:content = "")。

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

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

---

为了解决这个问题你需要将 `string` 对象编码为 `byte`,因为你使用了 `'wb'` 写入文件

```python
>>> string_like_object.encode('utf-8') + byte_like_object
b'This is some string type This is byte string'
英文:

You are reading using the following:

with open(d, &quot;rb&quot;) as r: data = r.read()

And trying to write using the following:

with open(file_n, &#39;wb&#39;) as f: f.write(content + data)

There is no problem with that except of this content + data.
You are trying to concatenate str object to byte (content variable declared as follow content = &quot;&quot;).

The following code will reproduce the same problem:

&gt;&gt;&gt; byte_like_object = b&#39;This is byte string &#39;
&gt;&gt;&gt; type(byte_like_object)
&lt;class &#39;bytes&#39;&gt;
&gt;&gt;&gt; string_like_object = &#39;This is some string type &#39;
&gt;&gt;&gt; type(string_like_object)
&lt;class &#39;str&#39;&gt;

&gt;&gt;&gt; string_like_object + byte_like_object

Traceback (most recent call last):
  File &quot;&lt;pyshell#13&gt;&quot;, line 1, in &lt;module&gt;
    string_like_object + byte_like_object
TypeError: can only concatenate str (not &quot;bytes&quot;) to str

In order to solve this issue you need to encode the string object to byte because you are writing to the file with &#39;wb&#39;.

&gt;&gt;&gt; string_like_object.encode(&#39;utf-8&#39;) + byte_like_object
b&#39;This is some string type This is byte string&#39;

huangapple
  • 本文由 发表于 2020年1月3日 18:43:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定