[英]read specific line in csv file , python
在使用 python 的CSV
文件中,我們可以逐行或逐行讀取所有文件,我想讀取特定行(行號 24 示例)而不讀取所有文件和所有行。
您可以使用linecache.getline :
linecache.getline(文件名,lineno[,module_globals])
從名為 filename 的文件中獲取 linelineno。 這個函數永遠不會引發異常——它會在出現錯誤時返回 ''(找到的行將包含終止換行符)。
import linecache
line = linecache.getline("foo.csv",24)
或者使用 itertools 中的消耗配方來移動指針:
import collections
from itertools import islice
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
with open("foo.csv") as f:
consume(f,23)
line = next(f)
或者,您可以利用熊貓中的nrows
和skiprows
參數
line_number = 30
pd.read_csv('big.csv.gz', sep = "\t", nrows = 1, skiprows = line_number - 1)
記住skiprows
可以是一個列表,所以如果你需要標題使用
pd.read_csv('big.csv.gz', sep = "\t", nrows = 1, skiprows = list(range(1, line_number - 1)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.