Python Forum
Data csv file into different text files with Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Data csv file into different text files with Python (/thread-3647.html)



Data csv file into different text files with Python - Bambi - Jun-10-2017

I'm a beginner in programming, but for a Dutch text categorization experiment I want to turn every instance (row) of a csv file into separate .txt files. The texts make up my dataset which has to be analyzed by a NLP tool. The header of my csv looks like this: ID Label Taaloefening1 Taaloefening2

Each instance has text in either the column 'Taaloefening1' or in the column 'Taaloefening2'. Now I need to save the text per instance in a .txt file and the name of the file needs to be the id and the label.
I was hoping I could to this automatically by programming a script in Python by using the csv module. I may have an idea about how to save the text into a .txt file, but I have no idea how to take the id and label, which match the text, as the file name.
Any ideas?


RE: Data csv file into different text files with Python - Ofnuts - Jun-11-2017

A file name is just a string that you can create by splicing other strings. So assuming you can read the CSV line into id, label and data,

with open(id+'_'+label+'.txt','w') as linefile:
   linefile.write(data)