2

I am working my way through Learn Python the Hard Way and am stuck on the extra credit for exercise 16. I am trying to read a file that I created using the main exercise 16. The code I wrote is as follows:

# pylint: disable-msg=C0103
""" This script reads and prints a file set from the argv """
from sys import argv

filename = argv

txt = open(filename)

print txt.read()

The file I am trying to read is:

Derp Derp
Reading this file
Will it work?

I am receiving the error: TypeError: coercing to Unicode: need string or buffer, list found but am unsure how my file is a list rather than strings.

3 Answers 3

6

To debug, try printing filename

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks! By printing filename, I discovered that filename was an array, or I suppose Python calls it a list? Anyways, I finished unpacking argv by changing filename = argv to script, filename = argv and everything worked swimmingly. I appreciate you teaching me to cook rather than just feeding me.
3

argv is a list of arguments to your script. The first argument is argv[1]. Try this:

from sys import argv

txt = open(argv[1])

print txt.read()

Important note: almost always the first item in a list is the 0th item, argv is an exception because the 0th argument is your script name.

1 Comment

That makes sense, I didn't know thats how argv worked, I alternatively changed filename = argv to script, filename = argv. I appreciate this answer and only chose dbr's as the correct one as I'll be able to use that one as inspiration in debugging future problems I come up with.
0

I too faced the same error but solved it with this code:

from sys import argv

txt = open(argv[1])

print txt.read()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.