Reputation: 167
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 = {}
Upvotes: 0
Views: 2395
Reputation: 833
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']
Upvotes: 0
Reputation: 1065
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
Upvotes: 1