Search code examples
pythontkintertext-fileseasygui

How do I write multi enter box input into .txt?


How do I make it so that "file.write(repr(fieldNames1))" writes what I input into "fieldNames1"?

import easygui

#Multi Enter Box
fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXAMPLE: Mad & Stressed)','Behavior:(EXAMPLE: Arguing with family)']

#Write to file
file = open('Fieldnames test.txt', 'a')
file.write(repr(fieldNames1))
file.close()

Makes a file called "Fieldnames test.txt" with the following text regardless of what I input into "fieldnNames1".

['Situation:(Example: Waiting for a friend who is late.)', 'Thoughts:(EXAMPLE: My friend Bob is always late!)', 'Emotions:(EXAMPLE: Mad & Stressed)', 'Behavior:(EXAMPLE: Arguing with family)']


Solution

  • The problem is that calling repr() on the list will create a single string from the list. What you're wanting is something like:

    f = open('output.txt', 'a')
    f.write('\n'.join(fieldNames1))
    f.close()
    

    The write() method doesn't automatically create newlines, so you have join() the list of strings together using a newline that's appropriate for your platform (such as \n). You can read more about file objects over at the Python documentation.

    Also, I recommend using a different variable than file, since file is actually a Python function. The code will work, but you should be aware of the potential for surprises.