Python 3.4 CSV 使用 in 函数删除项目

标签 python csv python-3.x

这是我当前的代码,我当前的问题是搜索不返回任何内容。如何获得此变量的字符串值。

count = 0
with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        row_count = sum(1 for row in myFile)
        print("aba")
        for x in range(row_count):
            print("aaa")
            for row in myFile:
                search = row[count].readline
                print(search)
                if self.delName.get("1.0","end-1c") in search:
                    count = count + 1
                else:
                    newFile.write(row[count])
                    count = count + 1

输出为:

aba
aaa
aaa

所以它运行了两次,这很好,因为我的 userDatabase 由两行数据组成。

相关文件包含以下数据:

"lukefinney","0000000","0000000","a"
"nictaylor","0000000","0000000","a"

最佳答案

您不能多次迭代打开的文件而不将文件对象倒回到开头。

您需要添加一个 file.seek(0) 调用,以便每次您想要再次从第一行开始读取时将文件读取器返回到开头:

myFile.seek(0)
for row in myFile:

你的代码的其余部分没有什么意义;迭代文件时,您会从文件中获取单独的行,因此每个 row 都是一个字符串对象。对字符串进行索引会为您提供仅包含一个字符的新字符串;例如,'foo'[1] 是字符 'o'

如果您想跨与字符串不匹配的行进行复制,则根本不需要预先知道行数。您在这里不处理行列表,您可以单独查看每一行:

filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        for row in myFile:
            if filter_string not in row:
                newFile.write(row)

这会进行子字符串匹配。如果需要匹配整列,请使用 csv module为您提供要匹配的各个列。该模块处理列值周围的引号:

import csv

filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv", "r", newline='') as myFile:
    with open("newFile.csv", "w", newline='') as newFile:
        writer = csv.writer(newFile)
        for row in csv.reader(myFile):
            # row is now a list of strings, like ['lukefinney', '0000000', '0000000', 'a']

            if filter_string != row[0]:  # test against the first column
                # copied across if the first column does not match exactly.
                writer.writerow(row)

关于Python 3.4 CSV 使用 in 函数删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30074777/

相关文章:

python - 如何将 MNIST 图像加载到 Pytorch DataLoader 中?

python - Apache 无法识别 Django 自定义身份验证后端

python - 在 XMPPpy 中禁用 SSL?

python - Python 给函数参数赋值的过程是怎样的?

python - 对这个数据帧进行下采样我哪里出了问题?

python - Python 中 @classmethod 的用途是什么?

python - 尾随定界符混淆了 pandas read_csv

apache - 如何将 HTTP 请求默认为服务器名后跟 JMeter 中的路径

PHP/MYSQL上传,导入.csv文件到mysql-process-table design

python - 每次我运行 "jupyter notebook"时,为什么我总是在 mac os 上得到这个?