I’ve built a script that takes a filename as an argument and extracts all lines that match a certain pattern. Trouble is I can’t open the filename – I keep getting :
"TypeError: coercing to unicode: need string or buffer"
It’s complaining about the line info = open(name, 'r').
Here’s 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 with
`extract.py trunc.log`
Any ideas what I’m doing wrong?
sys.argv[1:]is a list, not a string. When you slice a list, you get a list back — even if you only take 1 element with the slice. You need to giveopena string. Perhaps you wantedsys.argv[-1](the last element)?As a side note, the python standard library provides commandline parsing options — One is the excellent
argparsemodule which was introduced in python 2.7, but can be installed with very minimal effort on older python versions (I use it with python2.6 regularly).