簡體   English   中英

Python CSV 作為字典讀入,第 n 行為 header

[英]Python CSV read in as dictionary with nth row as header

我正在嘗試使用csv.DictReader讀取 CSV 文件以獲取字典數據。
問題是文件包含幾行其他數據,字典的 header 從第 n 行開始。

有沒有辦法在打開csv文件時指定起始行?

with open(filename, 'r') as f:
   reader = csv.DictReader(f) #want to specify the starting row here
   for row in reader:
      ...

由於 reader 對打開的文件 object 進行操作,您可以通過提前調用readline()自己跳過這些行:

from io import StringIO
from csv import DictReader

data = StringIO(
    """linewedon'twant
linewedon'twant
x,y
0,1
1,5
2,10
"""
)

with data as f:
    for _ in range(2):
        f.readline()

    reader = DictReader(f)
    for row in reader:
        print(row)

顯然, with data as fwith open("csv") as f: ; 我將它留在此處(不需要它的地方)以保持結構不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM