【问题标题】:Remove multiple lines from csv从 csv 中删除多行
【发布时间】:2018-01-08 21:47:06
【问题描述】:

到目前为止,这是我的代码,我想保留 CSV 中的许多行,但如果是第 3 行,则忽略

如果不是第三行,我想省略这行:

Curriculum Name,,Organization Employee Number,Employee Department,Employee Name,Employee Email,Employee Status,Date Assigned,Completion Date,Completion Status,Manager Name,Manager Email

它每 10 行左右出现一次,但如果它不是第一行(总是第三行),我希望将其删除

import csv, sys, os

#Read the CSV file and skipping the first 130 lines based on mylist
scanReport = open('Audit.csv', 'r')
scanReader = csv.reader(scanReport)

#search row's in csv - print out list 
for file in glob.glob(r'C:\sans\Audit.csv'):

    lineNumber = 0
    str - "Curriculum Name"

    with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
        writer = csv.writer(out)
            for row in csv.writer(inp):
                if row[2] != " 0":
                    writer.writerow(row)

【问题讨论】:

  • 你可能想问一个问题,因为目前我投票结束这个问题,因为不清楚这个问题可能是什么。不过,请务必查看网站指南如何提出好的问题!

标签: python python-3.x csv


【解决方案1】:

你想要在那个循环中这样的东西:

index = 0
for row in csv.writer(inp):
    if (index != 3) or (index == 3 and row[2] != " 0"):
        writer.writerow(row)
    index += 1

我不熟悉 csv 模块,所以我保留了你所有的东西,假设它是正确的(我认为你不需要那个模块来做你正在做的事情......)

更多关于enumeratehere的信息。

编辑: 要检查它是否是那条线:

def IsThatLine(row):
    return row[0] == "Curriculum Name" and row[1] == "" and row[2] == "Organization Employee" and ....

那么if可以变成:

if (index != 3) or (index == 3 and not IsThatLine(row)):

【讨论】:

  • 怎么办,不等于第三行?
  • 我已经编辑了我的if 行以使其更加明确:index != 3 确保除了第三行之外的所有行都被打印。 (index == 3 and row[2] != " 0") 确保仅在 row[2] != " 0" 时才打印第 3 行,这是您已经拥有的条件
  • 枚举是做什么的?
  • (你可以安全地删除index == 3,我只是想让代码更明确)
  • 我在答案中给出了enumerate函数的链接......book.pythontips.com/en/latest/enumerate.html
【解决方案2】:

能否请您更具体地回答您的问题? 您要删除包含以下描述的任何行吗?

课程名称、组织员工编号、员工部门、员工姓名、员工邮箱、员工状态、分配日期、完成日期、完成状态、经理姓名、经理邮箱

或者您是否只想删除此 csv 文件的第三行(行)?

【讨论】:

  • 您必须发表评论才能要求澄清。
  • 抱歉,刚开始回答问题。好课。但无论如何我无法添加评论。声望点数不足。
  • 对不起,我试图删除看起来不是 csv 文件中的第 3 行的行
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 2017-01-23
  • 1970-01-01
  • 2011-12-15
  • 2011-05-30
  • 2011-05-03
  • 1970-01-01
相关资源
最近更新 更多