CSV의 행을 필터링하고 새 CSV 파일에 저장

CSV의 행을 필터링하고 새 CSV 파일에 저장

csv 파일을 한 줄씩 필터링하고 if 조건을 충족하는 줄을 선택하고 싶습니다.

csv 파일은 쉼표로 구분되므로 코드는 다음과 같습니다.

'BEGIN {FS=','}
{while read line 
if (condition) 
   save selected line to a new csv file
} done < file.csv'

조건이 충족되면 선택한 행을 새 csv 파일에 저장하는 방법은 무엇입니까? 누구든지 몇 가지 예를 제공할 수 있습니까?

답변1

awk이렇게 사용하세요

awk -F, '(condition) { print >"to_new.csv"}' file.csv

필드를 구분하는 -F,쉼표 구분 기호를 지정합니다. ,만약에상황귀하의 기준과 일치하면 행을 to_new.csv.

우리는 사용했었다단일 " >" 리디렉션여기. 이러한 유형의 리디렉션을 사용하는 경우to_new.csv첫 번째 출력이 기록되기 전에 지워집니다. 후속 쓰기는 동일합니다.to_new.csv파일을 삭제하지 말고 추가하세요. (이것은 쉘 스크립트에서 리디렉션을 사용하는 것과 다릅니다.)to_new.csv존재하지 않고 생성됩니다.

아니면 간단히 다음과 같이 작성하세요:

awk -F, 'condition' file.csv > to_new.csv

답변2

나는 Python을 사용하여 이런 일을 할 것입니다. 예는 다음과 같습니다.

import csv

#Create a csv file with some data
myData = [["first_name", "second_name", "Grade"],
          ['Alex', 'Brian', 'A'],
          ['Tom', 'Smith', 'B']]

myFile1 = open('file1.csv', 'w')
with myFile1:
    writer = csv.writer(myFile1)
    writer.writerows(myData)

#Create a second csv file
myFile2 = open('file2.csv', 'w')

#Read the first file created with data
with open('file1.csv') as File:
    reader = csv.reader(File)
    for row in reader:
        #Print every row to the console
        print(row)
        if row[0] == "Alex":
           #If the first cell of the row says Alex, say hi and add the row to the second file
           print "Hi Alex"
           with myFile2:
             writer = csv.writer(myFile2)
             writer.writerow(row)

관련 정보