How to write each element of list in separate text file?
<p>I am trying to write each element of the list in a different file. </p>

<p>Let say we have a list:</p>

<pre><code>dataset = ['abc', 'def', 'ghi']
</code></pre>

<p>I want to loop through the list and create text files depending upon the length of the list. So, in this case, there should be 3 text files and each will have content abc, def and ghi respectively.</p>

<p>My current code is below:</p>

<pre><code># This will read a text file, normalize it and remove stopwords from it using nltk.
import nltk, io, math
from nltk.corpus import stopwords

# Read raw text
targetFile = open('text.txt')
rawtext = targetFile.read()

# Removing stopwords
stops = set(stopwords.words('english'))
filtered_text = [i for i in rawtext.lower().split() if i not in stops]

# Count Number of words
total_words = len(filtered_text)

# Divide them equally into 10 different lists
chunk_size = math.floor(total_words/10)
n_lists_of_words = [filtered_text[i:i + chunk_size] for i in range(0, len(filtered_text), chunk_size)]
if(len(n_lists_of_words) &gt; 10):
    del n_lists_of_words[-1]

# Lets make list of strings instead of list of lists
list_of_str = [' '.join(x) for x in n_lists_of_words]


# Create 10 different files from above 10 elements of n_list_of_words list
for index, word in enumerate(n_lists_of_words):
    with io.FileIO("output_text_" + str(index) + ".txt", "w") as file:
        file.write(bytes(word), 'UTF-8')
</code></pre>

<p>Error message:</p>

<pre><code>Traceback (most recent call last):
  File "clean_my_text.py", line 35, in &lt;module&gt;
    file.write(bytes(word), 'UTF-8') 
TypeError: 'str' object cannot be interpreted as an integer
</code></pre>

<p>Your code is just a little bit wrong.
here is the last line corrected.
file.write(bytes(dataset[count], 'UTF-8'))</p>

python python-3.x