使用Python 3更新CSV文件(添加/删除行) [英] Updating CSV file (add/remove rows) with Python 3
问题描述
每天都有人,
我有一个Raspberry Pi系统,它跟踪各种用户检出的工具。我已经设置它,使得系统的扫描执行时,用户签入,以及当他们签出。通过比较两次扫描,我可以确定是否已经采用/返回了刀具。但是,我还有一个Log.csv文件,它跟踪哪些工具当前检出。我可以添加到这个日志当一个工具签出(这里没有问题),但我有麻烦在工具返回时删除该行。
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.
我搜索了SO为这个解决方案,但还没有找到任何具体的。根据我的理解,您无法从CSV文件中删除单个行?我将不得不重写该文件,并且该特定的行被省略?
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?
这里是我到目前为止,包括添加和删除行Log.csv文件:
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:
???
请记住,上述代码已简化,以保持简洁。我想如果tools_returned在读者行是太含糊。我可以将其更改为:
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!
推荐答案
我不认为 csv
是这里的正确结构。你想能够查找一个给定的工具,找出它的 tools_taken
是True还是改变它的 tools_taken
或者从文件中删除工具,或者向文件中添加工具,是吗?
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?
这是数据库的用途,例如 shelve
:
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']
换句话说,你可以只是一个 dict
这种情况下,充满 dict
s),但它会自动持续运行。
In other words, you can just it just like a dict
(in this case, full of dict
s), but it's automatically persistent across runs.
这篇关于使用Python 3更新CSV文件(添加/删除行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!