python - 如何在 csv 文件中查找元素并编辑该文件

标签 python python-3.x csv

我正在尝试使用 kivy 创建一个程序,该程序接受输入,检查该值是否在 csv 内,并根据该人的位置添加小时数。

现在我正在尝试弄清楚如何检查输入是否在 csv 文件中,但我什么也没得到。

(我只需要逻辑/方法方面的帮助)

(我一个月前才开始编码,之前有一点经验,所以我有点迷失)

我尝试遍历行并遍历行中的每个字段来检查输入。我运行它,但我什么也没得到。请帮忙。提前致谢。

def sign_in(self, text_input):
    self.text_input = text_input
    with open('test.csv', 'r') as fp:
        reader = csv.reader(fp, delimiter=',')
        t = list(reader)
        i = 0
        for x in t:
            i += 1
            for field in x:
                if self.text_input == field:
                    if x[0] == "Vice President":
                        a = x[6]
                        a = 3.5 + int(a)
                        x[6] = a
                        fp.write(t[i])
                        self.signin()
                    else:
                        self.fk()
        else:
            self.noUser()
    fp.close()

csv 文件

职位、姓名、学校、年级、电子邮件、电话号码、工作时间

副校长,约翰·帕克,高中,11,burger@gmail.com,1234567890,0

csv 文件应该随着该行中添加的小时数而变化

最佳答案

如果您尝试通过搜索名称来编辑 csv 文件,我会使用标题作为值的占位符,这样您就不会依赖位置:

import csv

with open('test.csv', 'r') as fh:
    reader = csv.reader(fh)
    # get the headers out first, which is the first line
    headers = next(reader)

    for line in reader:
        # this will make a dictionary with the header values as
        # keys and the line entries as values
        # use l.strip to avoid the spaces following commas
        entry = dict(zip(headers, (l.strip() for l in line)))

        # use key access, it makes the code a bit more readable
        if entry['name'] == text_input.strip(): # strip leading and trailing whitespace
            print(line)

dict(zip(header, line)) 并不比仅使用 line[0] == text_input 更快,但是如果您尝试操作多个值(value)观,我认为明确性更好一些。不过,这更多的是一种风格,可以根据您的用例进行争论。

现在,更大的问题是您尝试在以只读访问权限打开的文件上调用 fp.write:

with open('file.txt') as fh:
    fh.write('a')

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
io.UnsupportedOperation: not writable

要解决此问题,您可以将新内容写入新文件,然后在完成后覆盖现有文件:

import os

with open('test.csv') as infile,
     open('new.csv', 'w') as outfile:
     for line in infile:
         # do things
         outfile.write(line)

# then when the method is complete
# move test.csv to new.csv, which overwrites the file
os.replace('new.csv', 'test.csv')

关于python - 如何在 csv 文件中查找元素并编辑该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742346/

相关文章:

regex - Notepad++ CSV 拆分和删除字段

powershell - 使用 csv 通过 powershell 在 office 365 中分配许可证

python - 从 django rest 框架中使用 api

python - 使用 python 导入我的数据库连接

python - 考虑到某些限制,随机化循环赛赛程

list - 如果列表重复n次,如何删除列表中的所有字母。其中 n 是 1-10 之间的数字

python - pandas read_csv 中的编解码器问题

python - Cron 作业无法使用 admin_required 装饰器访问 url

python - 由于不支持地址系列错误,无法从 Python 发送电子邮件

python - 如何在 Heroku 上执行 python 脚本?