반응형
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
반응형
'파이썬' 카테고리의 다른 글
파이썬 교차 모듈 변수를 만드는 방법은 무엇입니까? (0) | 2021.01.28 |
---|---|
파이썬 Django의 사용자 지정 관리자에서 DoesNotExist 예외 잡기 (0) | 2021.01.28 |
파이썬 다른 함수를 반환하는 함수를 어떻게 작성합니까? (0) | 2021.01.28 |
파이썬 Python 용 yaml 패키지를 어떻게 설치합니까? (0) | 2021.01.28 |
파이썬 IPython 노트북에서 대화 형 matplotlib 창을 어떻게 열 수 있습니까? (0) | 2021.01.28 |
댓글