문제 설명
DictReader가 내 파일의 두 줄을 건너뛰고 있습니까? (DictReader is skipping two lines of my file?)
다음 형식의 csv 파일이 있습니다.
date, open, high, low,..
22‑11‑14, 660.6, 15.1, 12.6
22‑11‑13, 569.6, 13.1, 10.2
22‑11‑12, 716.0, 18.6, 13.2
....
csv로 파일을 열 때 .DictReader를 실행한 다음 데이터를 행별로 읽으면 헤더 날짜, 열기 등을 건너뜁니다. 그러나 그것은 또한 데이터의 첫 번째 행을 건너 뛰고 있습니까 ?? 날짜 22‑11‑14의 데이터를 건너뛰고 22‑11‑13으로 시작합니까?? 여기 내 코드가 있습니다. 왜 이것이 무엇이며 어떻게 해결할 수 있는지 아시는 분 계신가요??
types = [("Date", str), ("Open", float), ("High", float),
("Low", float), ("Close", float), ("Volume", int), ("Adj Close", float)]
input_file = csv.DictReader(open("googlePrices.csv"))
dataList = []
for rows in input_file:
rows.update((key, conversion(rows[key])) for key, conversion in types))
rows['Date'] = time.strptime(rows['Date'], '%Y‑%m‑%d')
dataList.append(rows)
그래서 데이터 목록 목록에서 첫 번째 요소는 22‑11‑13에 대한 데이터이고 그 다음부터는 거기에서 완벽하게 작동합니다. 하지만 목록에 넣으려면 22‑11‑14가 필요합니까?
참조 솔루션
방법 1:
If your file is really formatted as you describe, you may need to put commas between the column names
date, open, high, low
방법 2:
I found a link to a googlePrices.csv file on the internet. I took your basic script and cleaned it up a bit below:
import csv
import time
types = [("Date", lambda d: time.strptime(d, '%Y‑%m‑%d')), ("Open", float), ("High", float),
("Low", float), ("Close", float), ("Volume", int),
("Adj Close", float)]
with open("googlePrices.csv") as f:
input_file = csv.DictReader(f)
dataList = []
for rows in input_file:
rows.update((key, conversion(rows[key])) for key, conversion in types)
dataList.append(rows)
print dataList[0] # shows the first row
Here are the first two rows of the file:
$ head ‑n 2 googlePrices.csv
"Date","Open","High","Low","Close","Volume","Adj Close"
"2012‑11‑14",660.66,662.18,650.5,652.55,1668400,652.55
This is my output:
$ python reader.py
{'Volume': 1668400, 'Adj Close': 652.55, 'High': 662.18, 'Low': 650.5, 'Date': time.struct_time(tm_year=2012, tm_mon=11, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=319, tm_isdst=‑1), 'Close': 652.55, 'Open': 660.66}
Your code as shown does not have any issues with it. Either there is something wrong with the file with non printable characters, or your code isn't as you pasted it. I am also pretty sure this is some kind of homework problem based on my Google‑fu.
(by CuriousDog、xianthrops、Josh J)