티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to read one single line of csv data in Python?
Python에서 CSV 데이터의 한 줄(line)을 읽는 방법은?
문제 내용
There is a lot of examples of reading csv data using python, like this one:
Python을 사용하여 CSV 데이터를 읽는 많은 예시들이 있습니다. 예를 들어, 다음과 같은 것입니다:
import csv
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
print(row)
I only want to read one line of data and enter it into various variables. How do I do that? I've looked everywhere for a working example.
하지만 저는 오직 하나의 데이터 줄만 읽어서 여러 변수에 입력하고 싶습니다. 이를 어떻게 할 수 있을까요? 동작하는 예제를 찾기 위해 많은 곳을 찾아봤지만 찾지 못했습니다.
My code only retrieves the value for i, and none of the other values
제 코드는 i의 값을 반환하지만 다른 값들은 반환하지 않습니다.
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
i = int(row[0])
a1 = int(row[1])
b1 = int(row[2])
c1 = int(row[2])
x1 = int(row[2])
y1 = int(row[2])
z1 = int(row[2])
높은 점수를 받은 Solution
To read only the first row of the csv file use next()
on the reader object.
CSV 파일의 첫 번째 행만 읽으려면, reader 객체에 next()를 사용하십시오.
with open('some.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader) # gets the first line
# now do something here
# if first row is the header, then you can do one more next() to get the next row:
# row2 = next(f)
or :
또는 :
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
# do something here with `row`
break
가장 최근 달린 Solution
To print a range of line, in this case from line 4 to 7
4에서 7까지의 행을 출력하려면 다음을 사용하십시오.
import csv
with open('california_housing_test.csv') as csv_file:
data = csv.reader(csv_file)
for row in list(data)[4:7]:
print(row)
출처 : https://stackoverflow.com/questions/17262256/how-to-read-one-single-line-of-csv-data-in-python
'개발 > 파이썬' 카테고리의 다른 글
딕셔너리 리스트에서 특정 키의 값 리스트로 가져오기 (0) | 2023.03.07 |
---|---|
상위 디렉토리에서 파일을 가져오는 방법 (0) | 2023.03.06 |
데이터프레임의 열 정규화 (0) | 2023.03.04 |
파이썬 딕셔너리 저장하기 (0) | 2023.03.03 |
맥에서 pip 루트 권한 실행시 "Permission Denied" 오류 발생 (0) | 2023.03.03 |