본문 바로가기
파이썬

파이썬 Python을 사용하여 csv 파일을 편집 할 때 헤더 건너 뛰기

by º기록 2021. 1. 28.
반응형

Python을 사용하여 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)

 

참조 페이지 https://stackoverflow.com/questions/14257373

 

 

반응형

댓글