Q:

Wrting each item in a list into a separate txt file with auto-assigned filename (python=3.6)

I'm using textract to get plain text from PDF files. For the plain text of each PDF file in the directory, I append it to the list filetext_list. I want to write each item of the list to a separate txt file with an auto-assigned filename like "article_1". Here is what I did so far:
import textract
import os
filetext_list = []
directory=os.getcwd()
for file in os.listdir(directory):
    txt = textract.process(file, method = 'pdfminer')
    filetext_list.append(txt)
    for i in range(2):
        for filetext in filetext_list:    
            with open('artile_{0}.txt'.format(i),'w') as f:
                f.write(str(filetext))
        f.close()

The output files are "article_0" and "article_1", which are named properly. However, both files contain the text of the same item in the list. I intended them to each contain the text of a separate item in the list. Any idea why the code failed? Also, I would like to eliminate the "\n" elements in the text by doing something like .replace('\n', ' '), but I don't know where this would fit in the code. Thank you!

A:

What is it you're trying to do exactly?  I think I may be misunderstanding you.
The end result is basically that you want to convert each pdf to a txt file right?
import textract
import os
filetext_list = []
directory=os.getcwd()

for file in os.listdir(directory):
     txt = textract.process(file, method = 'pdfminer')
     filetext_list.append(txt)

for index, text in enumerate(filetext_list) :
     with open('article_{0}.txt'.format(index),'w') as f:
          f.write(str(text).replace("\n",""))

thus if your directory contents were [thing1.pdf, thing2.pdf, thing3.pdf] then the new files you generated would be article_0 (with contents of thing1.pdf), article_1 (with thing2.pdf's contents), article_2 (with contents of thing3.pdf)
I'm not sure how to give you pointers on where you went wrong with your code asynchronously.  But you would do better to restart your thinking on this than to try to continue using the logic that you currently have. 
Every new "open" coupled with a write is overwriting the original file.
So what you're getting is article_0 and article_1 with the contents of the last pdf in the list of the files in the directory.
Your loop with "range(2)" is also being called once for each file in your directory, so the contents of article_0 looks like "contents of the first file, then the contents of the first file again, then the contents of the second file, then the contents of the first file then the contents of the second file, then th e third, then the 1st -> 2nd -> 3rd -> 4th. and so on.
Additionally if you do "with open" you don't need to close the file.  It close automatically afaik.

