Search code examples
pythonlistdataframetext

Is it possible to turn _io.TextIOWrapper into a list?


I have a dataframe and wanted to turn one of the columns into a list:

my_list = df_mydata['column2'].tolist()

The output is:

['This was the first row',
 'And the second'
 'I have some [parantheses]' 
 'that (might) play a role later']

However, type(my_list) is _io.TextIOWrapper. I wrote a code that iterates through the list items and there might be a problem in the data itself (because of the parentheses and because of using re, but that's another story), so I wanted to save this output as a text file, and obviously have it as a list. But the following code doesn't work because it says it's unreadable:

with open('my_list.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

Can I just turn my_list into an actual list and then save it as .txt with the code above?


Solution

  • I try this and work correctly:

    df = pd.DataFrame({
        'column2': ['This was the first row',
                    'And the second',
                    'I have some [parantheses]' ,
                    'that (might) play a role later']
    })
    
    my_list = df['column2'].tolist()
    
    with open('my_list.txt', 'w') as f:
        for item in my_list:
            f.write("%s\n" % item)