【问题标题】:TypeError: descriptor 'encode' for 'str' objects doesn't apply to a 'tuple' objectTypeError:“str”对象的描述符“encode”不适用于“tuple”对象
【发布时间】:2020-03-18 17:57:08
【问题描述】:

请帮助修复 TypeError。它适用于 python 2,但不适用于 python 3。

Python2:

def ExchangeColumns(RECXX_Output,Modified_Recxx_Output,column1,column2,column3,column4,column5,column6):
with open(RECXX_Output) as infile ,open(Modified_Recxx_Output, 'wb') as outfile:
        reader = csv.DictReader(infile)
        append = (column1,column2,column3,column4,column5,column6)
        outfile.write(','.join(append)+'\n')

Python3:

def ExchangeColumns(RECXX_Output,Modified_Recxx_Output,column1,column2,column3,column4,column5,column6):
    with open(RECXX_Output) as infile ,open(Modified_Recxx_Output, 'wb') as outfile:
        reader = csv.DictReader(infile)
        append = (column1,column2,column3,column4,column5,column6)
        appendb =  str.encode(append)
        outfile.write(b','.join(appendb)+b'\n')
        ##outfile.write(b','.join(append).encode(encoding='utf-8')+b'\n')

【问题讨论】:

  • 需要最少的可重现代码来帮助您找到解决方案
  • 另外,你为什么把它写成字节串? outfile.write(b','.join(appendb)+b'\n') 而不仅仅是 outfile.write(','.join(appendb)+'\n')?
  • outfile.write(','.join(appendb)+'\n') - 仍然出现相同的错误 - TypeError: 'str' 对象的描述符 'encode' 不适用于“元组”对象

标签: python python-3.x type-conversion ride


【解决方案1】:

答案就在问题中——你有一个元组对象而不是字符串。

【讨论】:

  • 请告诉我是否有办法将上述python2代码转换为python3。对于其他线程/站点上建议的大多数方法,我都遇到了错误
【解决方案2】:

将文件打开为 'w' 而不是 'wb' 后它工作了

with open(RECXX_Output) as infile ,open(Modified_Recxx_Output, 'w') as outfile:

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 2021-09-14
    • 2022-01-21
    • 2020-11-01
    • 2022-11-26
    • 2022-07-22
    • 2020-06-30
    • 2021-07-01
    相关资源
    最近更新 更多