programing

Python을 사용하여 csv 파일을 처리할 때 헤더를 건너뛰는 방법은 무엇입니까?

javajsp 2023. 6. 18. 12:09

Python을 사용하여 csv 파일을 처리할 때 헤더를 건너뛰는 방법은 무엇입니까?

아래 참조 코드를 사용하여 파이썬을 사용하여 csv를 편집하고 있습니다.코드에서 호출된 함수는 코드의 윗부분을 형성합니다.

문제:나는 아래 참조된 코드가 두 번째 행부터 csv 편집을 시작하기를 원하며, 헤더가 포함된 첫 번째 행은 제외하기를 원합니다.지금은 첫 번째 줄에만 기능을 적용하고 있고, 머리글 행이 변경되고 있습니다.

in_file = open("tmob_notcleaned.csv", "rb")
reader = csv.reader(in_file)
out_file = open("tmob_cleaned.csv", "wb")
writer = csv.writer(out_file)
row = 1
for row in reader:
    row[13] = handle_color(row[10])[1].replace(" - ","").strip()
    row[10] = handle_color(row[10])[0].replace("-","").replace("(","").replace(")","").strip()
    row[14] = handle_gb(row[10])[1].replace("-","").replace(" ","").replace("GB","").strip()
    row[10] = handle_gb(row[10])[0].strip()
    row[9] = handle_oem(row[10])[1].replace("Blackberry","RIM").replace("TMobile","T-Mobile").strip()
    row[15] = handle_addon(row[10])[1].strip()
    row[10] = handle_addon(row[10])[0].replace(" by","").replace("FREE","").strip()
    writer.writerow(row)
in_file.close()    
out_file.close()

나는 초기화를 통해 이 문제를 해결하려고 했습니다.row에게 가변적인.1하지만 그것은 작동하지 않았다.

이 문제를 해결하는 데 도움을 주세요.

당신의.reader변수를 반복할 수 있습니다. 변수를 반복하면 행을 검색할 수 있습니다.

루프 전에 하나의 항목을 건너뛰려면 호출하고 반환 값을 무시하기만 하면 됩니다.

코드를 조금 단순화할 수도 있습니다. 열려 있는 파일을 컨텍스트 관리자로 사용하여 자동으로 닫힙니다.

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

헤더를 처리되지 않은 상태로 출력 파일에 쓰려면 출력을 전달하는 것도 쉽습니다.next()로.writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

이 문제를 해결하는 또 다른 방법은 DictReader 클래스를 사용하는 것입니다. DictReader 클래스는 헤더 행을 "건너"하고 이를 사용하여 명명된 인덱싱을 허용합니다.

다음과 같이 "foo.csv"가 주어집니다.

FirstColumn,SecondColumn
asdf,1234
qwer,5678

DictReader를 다음과 같이 사용합니다.

import csv
with open('foo.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print(row['FirstColumn'])  # Access by column header instead of column number
        print(row['SecondColumn'])

하고있다row=1루프 결과로 덮어쓰게 되므로 아무것도 변경되지 않습니다.

당신이 하고 싶은 것next(reader)한 줄 건너뛰기

다음()을 사용하여 한 번만 반복합니다.

with open(filename) as file:

    csvreaded = csv.reader(file)
    header = next(csvreaded)

    for row in csvreaded:
        empty_list.append(row) #your csv list without header  

또는 판독기 개체의 끝에 [1:]를 사용

with open(filename) as file:

    csvreaded = csv.reader(file)
    header = next(csvreaded)

    for row in csvreaded[1:]:
        empty_list.append(row) #your csv list without header  

마르틴 피터스의 반응에 영감을 받았습니다.

헤더를 삭제하기만 하면 되는 경우csv표준 Python 파일 I/O 라이브러리를 사용하여 작성하면 CSV Python 라이브러리를 사용한 쓰기 작업을 피할 수 있습니다.

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())

언급URL : https://stackoverflow.com/questions/14257373/how-to-skip-the-headers-when-processing-a-csv-file-using-python