Python 3连接'str'和'bytes'文件路径名

问题描述 投票:0回答:1

我想将现有的python 2脚本迁移到python 3,以下方法在py2中有效,但在py3中无效:

file_path = "subfolder\a_file.bin"

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

这里所做的只是获取一个文件路径,并在该子文件夹中添加带有".cap"的扩展名

所以我这样修改了它:

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

我收到错误:

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

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

我也尝试过这样的绝对路径:

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打印了file_n以确保其正确的文件路径,但是即使这样也会引发上述错误。如何将这个额外的/第二个文件扩展名添加到".bin",然后打开该文件?

python-3.x concatenation filepath bytestring
1个回答
0
投票

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

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

并尝试使用以下内容进行书写:

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

content + dataexcept没有问题。您正在尝试将str对象连接到byte。声明为contentcontent = ""变量。

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

为了解决此问题,您需要将encide对象string设置为byte,因为您正在使用'wb'写入文件。

>>> string_like_object.encode('utf-8') + byte_like_object
b'This is some string type This is byte string'
© www.soinside.com 2019 - 2024. All rights reserved.