我想将现有的 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)
我打印了 file_n
以确保其文件路径正确,但即使这样也会引发上述错误。如何将此额外/第二个文件扩展名添加到 ".bin"
中,然后打开该文件?
最佳答案
您正在使用以下内容阅读:
with open(d, "rb") as r: data = r.read()
并尝试使用以下内容进行编写:
with open(file_n, 'wb') as f: f.write(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'
。
>>> string_like_object.encode('utf-8') + byte_like_object
b'This is some string type This is byte string'
关于python-3.x - Python3将 'str'(不是 "bytes")连接到 'bytes' TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59577129/