Search code examples
pythonpathlib

Python 3.6 looking in wrong module/library ( _io.TextIOWrapper ) for function that should be called from pathlib


I am getting the following error from the code that follows, below:

AttributeError: '_io.TextIOWrapper' object has no attribute 'write_text'

Code:

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" comes from a result_list = cursor.fetchall()

The weird thing is this code is cut-and-pasted from a program that does not produce this error. Nothing is touching the object "output_filepath" in between when it gets instantiated and when it gets used in the "with" block.

I have searched The Google for the error and get zero hits (which was very surprising to me). I also looked over the various hits here (stackoverflow) that come up when you enter your "subject" for a new question.

I originally had "from pathlib import Path" as my import line, but changed it (along with the "output_filepath = ..." line) to what you see here, in my quest to find the problem.

I'm sure I'm doing something wrong somewhere, but I don't see what it is, and I don't understand why the code would work in the other program but not this one.


Solution

  • The two objects output_filepath and output_file in your codes have different classes/types, and because of that they have different methods you can use.

    You tried to use write_text, which is a method of the pathlib.Path object. However, when you're calling output_filepath.open(mode='w') you are getting an open file object in return. You can see it - Python says its type is _io.TextIOWrapper in the error message. Hence output_file.write_text doesn't work.

    This open file object does not have a write_text method, but does have the write method that most files or file-like objects have in Python.

    So this works:

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