Python 3.6 查找错误的 module/library ( _io.TextIOWrapper ) 应该从 pathlib 调用的函数

Python 3.6 looking in wrong module/library ( _io.TextIOWrapper ) for function that should be called from 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()

奇怪的是这段代码是从不会产生此错误的程序中剪切和粘贴的。在实例化和在 "with" 块中使用对象 "output_filepath" 之间没有任何内容。

我在 Google 中搜索了错误,结果为零(这让我非常惊讶)。我还查看了当您输入新问题 "subject" 时出现的各种点击 (Whosebug)。

我最初将 "from pathlib import Path" 作为我的导入行,但在我寻找问题的过程中将它(连同 "output_filepath = ..." 行更改为您在此处看到的内容。

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

您的代码中的两个对象 output_filepathoutput_file 具有不同的 classes/types,因此它们具有不同的方法供您使用。

您试图使用 write_text,它是 pathlib.Path 对象的一个​​方法。但是,当您调用 output_filepath.open(mode='w') 时,您会在 return 中获得一个 打开文件对象 。你可以看到它 - Python 在错误消息中说它的类型是 _io.TextIOWrapper。因此 output_file.write_text 不起作用。

这个打开的文件对象没有 write_text 方法,但有大多数文件或类文件对象在 Python.[=20= 中有的 write 方法]

所以这有效:

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])