Convert dataframe column into set of text files

I have a dataframe which contains topic and keywords column as shown below:

topic   keyword
    0   ['player', 'team', 'word_finder_unscrambler', ...
    1   ['weather', 'forecast', 'sale', 'philadelphia'...
    2   ['name', 'state', 'park', 'health', 'dog', 'ce...
    3   ['game', 'flight', 'play', 'game_live', 'play_...
    4   ['dictionary', 'clue', 'san_diego', 'professor...

Need to create a text file of each topic separately namely topic1.txt, topic2.txt,….topic20.txt and the topic text file should contain strings in newline inside keyword column something like this:

topic1.txt file should contain:

player
team
word_finder_unscrambler
etc

>Solution :

For each row of DataFrame create new txt file by name with topic column with add 1:

import csv

for t, k in zip(df['topic'], df['keyword']):
    with open(f"topic{t + 1}.txt","w") as f:
        wr = csv.writer(f,delimiter="\n")
        wr.writerow(k)

EDIT: Because no lists but strings in keyword column use:

import csv, ast

for t, k in zip(df['topic'], df['keyword']):
    with open(f"topic{t + 1}.txt","w") as f:
        wr = csv.writer(f,delimiter="\n")
        wr.writerow(ast.literal_eval(k))

Leave a Reply