Passing an argument in a python script and opening a file

I built a script that takes a file name as an argument and extracts all lines matching a specific pattern. The problem is that I cannot open the file name - I keep getting:

"TypeError: coercing to unicode: need string or buffer"

He complains about the string info = open(name, 'r').

Here is the code:

import re
import sys
print sys.argv[1:]

keyword = 'queued='
pattern = re.compile(keyword)

name = sys.argv[1:]
inf = open(name, 'r') 
outf = open("test.txt", 'w')

for line in inf:
    if pattern.search(line):
        outf.write(line)

And I call it

`extract.py trunc.log`

Any ideas what I'm doing wrong?

+5
source share
4 answers

sys.argv[1:]is a list, not a string. When you slice the list, you will get the list back - even if you take only 1 item with a slice. You must specify a string open. Perhaps you need sys.argv[-1](last item)?

python - One - argparse , python 2.7, python ( python2.6).

+7

:

name = sys.argv[1:]

name , . :

name = sys.argv[1]

argparse.

+2

sys.argv . ( ):

with open("test.txt", "w") as outf:
    for name in sys.argv[1:]:
        with open(name, 'r') as inf:
            ...

, test.txt ( ), , script. , try... except open(name,'r') ( ).

+1

optparse argparse

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

python 3.2 has an alternative (argparse) .

+1
source

All Articles