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

时间:2015-05-06 10:58:48

标签: 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"

2 个答案:

答案 0 :(得分:1)

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

每次要从第一行开始阅读时,您需要添加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)

如果要复制与字符串不匹配的行,则根本不需要事先了解行计数。您没有在这里处理行列表,您可以单独查看每一行:

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)

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

{{1}}

答案 1 :(得分:0)

一个问题是row_count = sum(1 for row in myFile)会消耗myFile的所有行。对myFile的后续读取将返回一个空字符串,表示文件结束。这意味着以后在您执行for row in myFile:的代码中的for循环未输入,因为所有行都已被使用。

解决此问题的方法是在myFile.seek(0)之前添加对for row in myFile:的调用。这将重置文件指针,然后for循环应该可以工作。

从您的代码中不太清楚您尝试做什么,但看起来您想过滤掉包含某个字符串的行。试试这个:

with open("userDatabase.csv","r") as myFile:
    with open("newFile.csv","w") as newFile:
        for row in myFile:
            if self.delName.get("1.0","end-1c") not in row:
                newFile.write(row)