Reading and writing files

I recently read the “Learn Python the Hard Way” online and did a little experiment with the python code involved in reading and writing files. But hold on, there seems to be a problem with the code. Everytime I want to save a file (i.e. write it), the IDLE showed and error:

Traceback (most recent call last):
  File "H:\gamesaver.py", line 13, in <module>
    target = open(filename, 'w')
TypeError: coercing to Unicode: need string or buffer, list found

Here is the original script (note: This is python 2.5.2):


from sys import argv

filename = argv
script = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file.  Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("
")
target.write(line2)
target.write("
")
target.write(line3)
target.write("
")

print "And finally, we close it."
target.close()

What could this possibly mean? :spin:

argv is a list of the command-line arguments; you need to specify the position of your filename and script strings in that list. From your code it appears you should say

 filename = argv[1]
 script = argv[2]

as argv[0] would be the command-line call to the script itself, iirc. Btw I think its use is limited to command-line calls from the interpreter, something like

$python myscript filename script

Is that how you want to use it?