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 give open
a string. Perhaps you wanted sys.argv[-1]
(the last element)?
As a side note, the python standard library provides commandline parsing options -- One is the excellent argparse
module 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).
This:
name = sys.argv[1:]
makes name
into a list of all arguments except the first. You mean:
name = sys.argv[1]
For real-world usage, you might want to look into argparse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With