1

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.

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

trees = open('trees.txt', 'w').write["Tree1", "Tree2", "Tree3"]

TypeError: 'builtin_function_or_method' object is not subscriptable

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!

Andrew LaPrise
  • 3,373
  • 4
  • 32
  • 50
lynkyra
  • 59
  • 5
  • 3
    You're not using properly the write method, you forgot parenthesis `trees = open('trees.txt', 'w').write("\n".join(["Tree1", "Tree2", "Tree3"]))` . I'd recommend you go through some of the existing [tutorials](https://docs.python.org/2/tutorial/inputoutput.html) out there – BPL Sep 14 '16 at 19:51

1 Answers1

3

Just apply write 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!).

Your fixed code (not the best there is, though):

open('trees.txt', 'w').write("\n".join(["Tree1", "Tree2", "Tree3"]))

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

note: this is a oneliner but not the proper way to go. Better use with open

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

that way you are sure that the file is closed properly when going out of scope

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thanks for your thorough answer! I have not learned how to use "with" yet, so I'm going to stick with the first line you suggested. I tried to assign the list to "trees" because in the next problem I have to print a specific item from the list through its index. I know how to answer that question, but I don't understand how I can assign my list to the variable "trees" so I can print from it. Do you have any suggestions? – lynkyra Sep 17 '16 at 00:49
  • just `trees = ["Tree1", "Tree2", "Tree3"]`. There are some good books & online tutorials you know :) – Jean-François Fabre Sep 17 '16 at 07:15