2016-10-05 1 views
-1

CSV 파일을 열려고하고 주어진 목록에 따라 일부 행을 제거하려고합니다. 같은 진행 상황에서 향후 사용을 위해 해당 행을 계산하려고합니다.행을 제거하고 동일한 파일 열기에서 개수를 계산하는 방법

각 파일 열기는 개별적으로 훌륭하게 작동합니다. 동일한 파일 열기 진행 상황에서 어떻게 결합 할 수 있습니까?

내 현재 코드는 다음과 같습니다

# read latest file and count rows 

with open(fileslst[-1], 'rb') as csvfile: 
csvReader = csv.reader(csvfile) 
for row in csvReader: 
    for alert in alertsCode: 
     if any(alert in row[11] for s in alertsCode) : 
      counter=counter+1 
print (str(counter)+" unnecessary codes in this file") 


#open and modify the latest file 

with open(fileslst[-1], 'rb') as csvfile: 
    csvReader = csv.reader(csvfile) 
    clean_rows = [row for row in csvReader if not any(alert in row[11] for alert in alertsCode)] 

with open(fileslst[-1], 'wb') as csvfile: 
    csv_writer = csv.writer(csvfile) 
    csv_writer.writerows(clean_rows) 

나는 그것이 작동하지 않습니다 같은 스크립트를 실행하지만, 별도로 것입니다 실행하는 경우.

내가 뭘 잘못하고 있니?

+0

을 최적화 할 수 있지만,이 하나의 해결책이 될 수있는 문제의 초기 설명에 따라 의미? – Goyo

+0

내가 카운터를 위해 열린 파일을 실행할 때 - 그것은 작업입니다. 삭제 행을위한 파일을 열 때, 그것은 작동합니다 ...하지만, 같은 스크립트에서 둘 다 실행할 때 그렇지 않습니다! –

+0

스크립트가 작동하는 대신 수행 할 작업은 무엇입니까? – Goyo

답변

0

가 확실히 "가 작동하지 않습니다"무엇

excluded = ['your excluded list here'] 
deleted_rows = 0 
with open(file) as read: 
    with open(file2) as write: 
     w = csv.writer(write) 
     r = csv.reader(read) 
     for row in r: 
      if row not in excluded: 
       w.writerow(row) 
      else: 
       deleted_rows += 1 
+0

하지만 같은 파일에서 수행해야합니다 ... "IOError : 쓰기 위해 파일을 열 수 없습니다." –

+0

원래 파일을 삭제하고 새로 생성 된 파일로 대체하는 옵션이 아닙니다. ? afaik 당신이 파이썬에서 csv 파일을 구문 분석하기로되어있는 방식은 입출력 파일을 갖는 것입니다. 입력 파일을 삭제하고 대체 할 수 없습니다. –

+0

난 그냥 이해가 안되는 이유는 별도로 작동하고 함께하지 않기 때문이다. –

관련 문제