G'day everyone,
I've got a Raspberry Pi system which keeps track of tools being checked out by various users. I've set it up such that a scan of the system is performed when a user checks in, as well as when they check out. By comparing the two scans, I can determine whether a tool has been taken/returned. However, I also have a Log.csv file which keeps track of which tools are currently checked out. I'm able to add to this log when a tool is checked out (no problems here), but I'm having trouble removing that row when the tool is returned.
I've searched SO for a solution to this, but haven't found anything concrete. From what I understand, you can't remove a single row from a CSV file? I would have to re-write the file, with that particular row being omitted?
Here's what I have so far, including both adding and remove rows on the Log.csv file:
with open('Log.csv', 'a+') as f:
reader = csv.reader(f)
if tools_taken not in reader:
csv.writer(open('Log.csv', 'a+')).writerow([tools_taken])
with open('Log.csv', 'a+') as f:
reader = csv.reader(f)
if tools_returned in reader:
???
Bear in mind that the above code is simplified to keep it succinct. I'm thinking that the 'if tools_returned in reader' line is too vague. I might change it to:
for row in reader:
for field in row:
if field == tools_taken:
???
Am I on the right track? Any input here would be very much appreciated!
解决方案
I don't think csv is the right structure here. You want to be able to look up a given tool, find out whether its tools_taken is True, or change its tools_taken, or remove a tool from the file, or add a tool to the file, right?
That's what a database is for, such as shelve:
import contextlib
import shelve
tools = shelve.open('Log.db', 'c', writeback=True)
with contextlib.closing(tools):
# Add a tool
tools['hammer'] = {'name': 'Hammer', 'owner': 'Joe', 'tools_taken': False}
# Check if a tool is taken
if tools['screwdriver']['tools_taken']:
print('The screwdriver is taken!')
# Change a tool's taken status:
tools['screwdriver']['tools_taken'] = True
# Remove a tool
del tools['jackhammer']
In other words, you can just it just like a dict (in this case, full of dicts), but it's automatically persistent across runs.