Python2转Python3脚本时遇writelines字节类型错误求助
Python2转Python3文件写入错误的解决方法
错误信息
"msg": "Write SQL ===> Problem writing sql script /tmp/ansible_xscchanlfy.sql [a bytes-like object is required, not 'str']"
问题根源
write_script函数以'ab'(二进制追加)模式打开文件,但处理列表类型的content时,直接写入了字符串而非字节对象。Python3严格区分字符串(str)和字节(bytes)类型,二进制文件流仅接受字节对象,这是报错的核心原因。
修正方案
方案1:保持二进制模式,统一编码处理
修改write_script函数,将列表中的每个字符串编码为字节后再写入:
def write_script(filename, content, owner='root'): with open(filename, 'ab') as out_file: if isinstance(content, list): # 遍历列表,将每个字符串编码为字节后写入 out_file.writelines((x + '\n').encode('utf-8') for x in content) else: out_file.write(content.encode('utf-8')) owner_pw = pwd.getpwnam(owner) os.chown(filename, owner_pw.pw_uid, owner_pw.pw_gid) os.chmod(filename, stat.S_IRWXU)
方案2:改用文本模式(更符合Python3习惯)
直接以文本追加模式打开文件并指定编码,无需手动处理字节转换:
def write_script(filename, content, owner='root'): with open(filename, 'a', encoding='utf-8') as out_file: if isinstance(content, list): out_file.writelines(x + '\n' for x in content) else: out_file.write(content) owner_pw = pwd.getpwnam(owner) os.chown(filename, owner_pw.pw_uid, owner_pw.pw_gid) os.chmod(filename, stat.S_IRWXU)
说明
两种方案均能解决问题:
- 方案1延续原二进制模式逻辑,仅补充列表元素的编码步骤;
- 方案2改用文本模式,让Python自动处理字符串到字节的编码转换,代码更简洁直观。
调用部分的代码无需修改,传入的args['sql']和cmd(字符串或字符串列表)均可被修正后的函数正确处理。
内容的提问来源于stack exchange,提问作者azad aawaraa
相关产品推荐
相关产品推荐

