How can I create a new file containing a list with a single line of code?
<p>I know this is probably very easy to do, but I am very new to coding. I can accomplish this in more than one line, but for my assignment it needs to be done in one line.</p>

<p>This is what I have, which raises an error that I don't understand.</p>

<pre><code>trees = open('trees.txt', 'w').write["Tree1", "Tree2", "Tree3"]
</code></pre>

<blockquote>
  <p>TypeError: 'builtin_function_or_method' object is not subscriptable</p>
</blockquote>

<p>I imagine that my problem is that I can't just tack on the "write" command where/how I did, but I am lost on how to do this correctly. Thanks in advance for any help or hints!</p>

<p>Just apply <code>write</code> on the file handle. To get proper text and not python list representation, you have to join the list into multiline text (if it's what you want!).</p>

<p>Your fixed code (not the best there is, though):</p>

<pre><code>open('trees.txt', 'w').write("\n".join(["Tree1", "Tree2", "Tree3"]))
</code></pre>

<p>BTW: I removed the assignment of <code>trees = open(...</code> since you get the return of the <code>write</code> operation which is <code>None</code></p>

<p>note: this is a oneliner but not the proper way to go. Better use <code>with open</code></p>

<pre><code>with open('trees.txt', 'w') as f: f.write("\n".join(["Tree1", "Tree2", "Tree3"]))
</code></pre>

<p>that way you are sure that the file is closed properly when going out of scope</p>

python list