首页 > 解决方案 > 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 = ...”行)更改为您在此处看到的内容。

我确定我在某处做错了什么,但我不明白它是什么,而且我不明白为什么代码可以在另一个程序中工作,但不能在这个程序中工作。

标签: pythonpathlib

解决方案


这两个对象在您output_filepathoutput_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])

推荐阅读