On 19/02/2013 4:07 PM, Hala Gamal wrote:
> ok, i have attached my code and the file i work on
> and also pasted it in pastebin :
http://pastebin.com/kZQ1pAVG
The code you pasted there doesn't do anything, and I don't see how it
could generate a LockError. But here's a quick sketch of how you could
use the csv module and whoosh.
I'll assume a CSV file formatted WITHOUT column headings in the first
row. For example:
iPod, 5, Plays music
iPad, 10, Shows websites
Mac Pro, 2, Makes websites
Here's how you could read the rows using csv and associate each column
value with a field name:
from whoosh import fields, index
import os.path
import csv
# This list associates a name with each position in a row
columns = ["name", "quantity", "description"]
schema = fields.Schema(name=fields.TEXT,
quantity=fields.NUMERIC,
description=fields.TEXT)
# Create the Whoosh index
indexname = "index"
if not os.path.exists(indexname):
os.mkdir(indexname)
ix = index.create_in(indexname, schema)
# Open a writer for the index
with ix.writer() as writer:
# Open the CSV file
with open("stuff.csv", "rb") as csvfile:
# Create a csv reader object for the file
csvreader = csv.reader(csvfile)
# Read each row in the file
for row in csvreader:
# Create a dictionary to hold the document values for this row
doc = {}
# Read the values for the row enumerated like
# (0, "name"), (1, "quantity"), etc.
for colnum, value in enumerate(row):
# Get the field name from the "columns" list
fieldname = columns[colnum]
# Strip any whitespace and convert to unicode
# NOTE: you need to pass the right encoding here!
value = unicode(value.strip(), "utf-8")
# Put the value in the dictionary
doc[fieldname] = value
# Pass the dictionary to the add_document method
writer.add_document(**doc)
(This could be much more compact but I've expanded some things for
clarity.) Of course if you want/need to use xlrd instead of csv, you
have to modify the example to use it. I'm not familiar with xlrd.
Cheers,
Matt