0

I'm trying open a txt file and read it, but I'm getting a type error and I'm unsure why. If you you could please provide a reasoning along with the correct syntax, I'm trying to get a better grasp of what's going on underneath. Here's the code, it's pretty simple I think:

from sys import argv

script = argv
filename = argv

txt = open(filename)

print "Here's your file %r" %filename
print txt.read()

Muchas Gracias

3 Answers 3

4

argv is a list, not a string. You want

script = argv[0]
filename = argv[1]

Consider using argparse instead of handing sys.argv directly:

>>> import argparse
>>> parser = argparse.ArgumentParser(description="Print a file.")
>>> parser.add_argument("path", type=str, nargs=1, help="Path to the file to be printed.")
_StoreAction(option_strings=[], dest='path', nargs=1, const=None, default=None, type=<type 'str'>, choices=None, help='Path to the file to be printed.', metavar=None)
>>> args = parser.parse_args()
>>> print args
Namespace(path=[<...>])

It looks much more complicated, but it will make your command-line utility much more flexible, easier to expand, and it will ensure you get proper documentation on the command line.

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

Comments

2

First of all, argv is a list of arguments. Open doesn't take a list. That's why you're getting a type error.

Second, open (should) take 2 parameters, the filename and the mode (yes mode is optional, but get in the habit of putting it there. Replace with

import sys

script = sys.argv[0]
filename = sys.argv[1]

txt = open(filename, 'r')

print "Here's your file %r" %filename
print txt.read()

5 Comments

Why get in the habit of putting a mode? The point of a default argument is that it's not always necessary.
Because I had to look up if mode was optional, and what the default value is. That means anyone reading this code might have to do the same. Which is bad.
Also add a binary or text mode flag. It makes a difference on Windows. And in Python it always makes a difference, so put it in.
Actually that's not true. It ONLY makes a difference on windows, and python just passes it on to the kernel.
Sorry, that should say "In Python 3 is always makes a difference." I must have slipped in the "3".
0

argv will be a list, while filename should be a string.

You should probably be using filename = argv[1]

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.