删除csv文件中正在使用的行

时间:2018-08-08 16:58:30

标签: python python-3.x csv

我正在尝试删除csv文件中正在使用的行,但不确定如何处理。我要删除文件中使用的第一行(不包括标题。我也要使用相同的文件,而不是创建新文件。这是到目前为止的内容:

if os.path.isfile('test.csv'):
    with open("test.csv", "r") as f_input:
        csv_input = csv.reader(f_input)
        next(f_input) #skips header
        for row in csv_input:
            item_c =row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            #DELETE THE ROW AFTER I GET THE INFO FOR EACH "item"

1 个答案:

答案 0 :(得分:1)

您可以重新创建输入文件,并删除特定的行,然后删除原始文件。您也可以通过将整个文件读入内存,然后删除一些行并重新创建它来完成此操作。但是,第二种方法风险更大。这是怎么回事:

import csv
if os.path.isfile('test.csv'):
   with open('test.csv', 'r') as inp, open('test_edited.csv', 'w') as out:
      writer = csv.writer(out)
      reader = csv.reader(inp)
      writer.writerow(next(reader)) #copy headers
      for row in reader:
            item_c = row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            if item_k != "someValue":  #Here you put any condition you want
               writer.writerow(row)    #Save only the rows that do not have someValue

最后,您可以删除原始文件

删除具有特定索引的行:

import csv
n_list = [1]
if os.path.isfile('test.csv'):
   with open('test.csv', 'r') as inp, open('test_edited.csv', 'w') as out:
      writer = csv.writer(out)
      reader = csv.reader(inp)
      writer.writerow(next(reader)) #copy headers
      index = 1
      for row in reader:
            item_c = row[0]
            item_l = row[1]
            item_v = row[2]
            item_k = row[3]
            if index not in n_list:  #Here you put any condition you want
               writer.writerow(row)    #Save only the rows that do not have someValue
            index+=1