0
votes

I'm writing a simple script to search a .txt document for a search word. The script so far will: • Prompt for a file name • Prompt for a word to search for

The prompts work, followed by "TypeError: coercing to Unicode: need string or buffer, list found". I've read other posts on this error, but can't identify why this is happening, so I can move on to the steps: • Open the file in Append mode • Append (print) the number of lines the keyword appears on in the file.

Please note: This worked until I added the user prompts.

import sys
import os

f = file(raw_input("Enter filename: "), 'a')
name_file = raw_input("Input search terms, comma separated: ").lower().split(",")
my_file = open(name_file, "a")
#removed {open(name_file}[0] from above line
search = [x.strip(' ') for x in f]
count = {}
2
Why are you trying to open the keywords list? - user4237459
Edited for clarity. I'm trying to search for a specific word in the file, I understand "keywords" has a different meaning. - Rampant
I know that it appears that you got further by posting a dup, but please don't do this again. Normally, this question would be closed as a dup of your existing question, but this one is worded better and seems to have helped. In the future, just make edits to your existing question. - Lynn Crumbling
Thanks @LynnCrumbling, I was under the impression I could not edit the original question, and told it wasn't specific enough. Should I delete the original? - Rampant
@Ender Sure, that would be a fine idea... Roomba would come along and delete it in a few days anyway (closed, and negative score question + answer), but cleaning up after yourself is always good :) - Lynn Crumbling

2 Answers

1
votes

string.split(",")

returns a list of strings. i.e:

>>myString = "Hello buddy, how are you?"

>>myList = mystring.split(",")

>>myList
["Hello buddy"," how are you?"]

name_file is a list, and your code explodes because open expects a string as its first argument, not a list

0
votes

I would suggest sys.argv.

You run a command:

$ myscript.py file.txt term1 term2 term3

Script:

import sys

print sys.argv

Output:

['./myscript.py', 'myscript.py', 'file.txt', 'term1', 'term2', 'term3']