2
votes

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

3 Answers

6
votes

To debug, try printing filename

3
votes

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.

0
votes

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

from sys import argv

txt = open(argv[1])

print txt.read()