python - Python 3.6 在错误的模块/库( _io.TextIOWrapper )中查找应该从 pathlib 调用的函数
问题描述
我从下面的代码中收到以下错误,如下:
AttributeError:“_io.TextIOWrapper”对象没有属性“write_text”
代码:
import pathlib
output_filepath = pathlib.Path(r'/home/john/somedir/data/somefilename.csv')
with output_filepath.open(mode='w') as output_file:
for line in result_list:
# Write records to the file
output_file.write_text('%s\n' % line[1])
“result_list”来自 result_list = cursor.fetchall()
奇怪的是,这段代码是从一个不会产生这个错误的程序中剪切和粘贴的。在对象“output_filepath”被实例化和在“with”块中使用之间,没有任何东西接触到它。
我已经在 Google 上搜索了错误并获得了零点击(这让我感到非常惊讶)。我还查看了当您为新问题输入“主题”时出现的各种点击(stackoverflow)。
我最初将“from pathlib import Path”作为我的导入行,但为了找到问题,将其(连同“output_filepath = ...”行)更改为您在此处看到的内容。
我确定我在某处做错了什么,但我不明白它是什么,而且我不明白为什么代码可以在另一个程序中工作,但不能在这个程序中工作。
解决方案
这两个对象在您output_filepath
的output_file
代码中具有不同的类/类型,因此它们具有您可以使用的不同方法。
您尝试使用write_text
,这是pathlib.Path
对象的一种方法。但是,当您打电话时,output_filepath.open(mode='w')
您会得到一个打开的文件对象作为回报。你可以看到它——Python 说它的类型_io.TextIOWrapper
在错误消息中。因此output_file.write_text
不起作用。
这个打开的文件对象没有write_text
方法,但有write
大多数文件或类文件对象在 Python 中的方法。
所以这有效:
import pathlib
output_filepath = pathlib.Path(r'/home/john/somedir/data/somefilename.csv')
with output_filepath.open(mode='w') as output_file:
for line in result_list:
# Write records to the file
output_file.write('%s\n' % line[1])
推荐阅读
- javascript - 手风琴 .glyphicon-chevron-up 和 .glyphicon-chevron-down 不起作用
- scala - Shapeless - 泛型上下文中的泛型
- java - TestNG 参数化:将浏览器类型传递给基类时出现 NullPointerException
- angular - 解析 Angular 通用服务中的通用参数
- bash - 我如何循环浏览一定数量的文件夹
- azure - Set-Variable 策略:不允许表达式返回类型
- python - 如何从其二进制代码加载图像
- node.js - node-red 使用多个来源构建 http post 请求
- php - PHP多维数组到两列HTML表
- gcc - LD:链接描述文件中的 ALIGN 与 SUBALIGN