python3 csv 模板_使用Python 3更新CSV文件(添加/删除行)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值