解决:TypeError: write() argument must be str, not tuple


解决:TypeError: write() argument must be str, not tuple





背景

在使用之前的代码时,报错:
Traceback (most recent call last):
File “E:/Test/test.py”, line 14, in
file.write(lines)
TypeError: write() argument must be str, not tuple



报错问题


Traceback (most recent call last):
  File "E:/Test/test.py", line 14, in <module>
    file.write(lines)
TypeError: write() argument must be str, not tuple



报错翻译

主要报错信息内容翻译如下所示:


Traceback (most recent call last):
  File "E:/Test/test.py", line 14, in <module>
    file.write(lines)
TypeError: write() argument must be str, not tuple

翻译:


追溯(最近一次通话):
文件“E:/Test/Test.py”,第14行,在<module>中
file.write(lines)
TypeError:write()参数必须是str,而不是tuple



报错位置代码


...
        lines = html.xpath('//div[@class="rank"]//span[@class="span"]') 
        file.write(lines)
...



报错原因

经过查阅资料,发现是这个错误产生的原因是在代码中,试图使用写入(write)函数将一个tuple对象写入某个文件,但是write函数要求的参数必须是字符串,而不是tuple对象。然后这样的错误提示就是这么产生的。

小伙伴们按下面的解决方法即可解决!!!



解决方法

要解决这个错误,需要检查你代码,确保在调用write函数时传入的参数是一个字符串。例如,可以将tuple对象转换为字符串,然后再使用write函数写入文件,代码如下。

正确的代码是:


...

        file.write(lines[0]) 
        
...

write(fd, str)

Write the bytestring in str to file descriptor fd.

Return the number of bytes actually written.

Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To write a “file object” returned by the built-in function open() or by popen() or fdopen(), or sys.stdout or sys.stderr, use its write() method.
Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).

write(fd, str)

将str中的字节串写入文件描述符fd。

返回实际写入的字节数。

注意:此函数用于低级I/O,必须应用于由os.open()或pipe()返回的文件描述符。编写由内置函数open()或popen()或fdopen()返回的“文件对象”。标准输出或系统。Stderr,使用其write()方法。
在3.5版更改:如果系统调用被中断,而信号处理程序没有引发异常,该函数现在会重试系统调用,而不是引发InterruptedError异常(原因请参阅PEP 475)。



今天的分享就到此结束了

欢迎点赞评论关注三连

在这里插入图片描述

  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ninghes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值