![](/img/trans.png)
[英]How to read only a specific range of lines out of a csv file with python?
[英]How can I use python to read only a certain range of lines in a .csv?
我正在嘗試處理一個巨大的.csv 文件,但我不需要前 ~900000 行數據。 這就是我最初試圖擺脫那塊數據的方式,但它使程序需要很長時間才能完成。 有沒有更直接的方法可以做到這一點,我什至一開始都沒有閱讀前 900000 行?
firstColumn = [ ]
secondColumn = [ ]
thirdColumn = [ ]
readFile = input("Enter name of file to be read: ")
with open(readFile,'r') as readFile:
for eachline in readFile: # converting columns to lists
parts = eachline.strip('\n').split(',')
firstColumn.append(parts[0])
secondColumn.append(parts[1])
thirdColumn.append(parts[2])
for j in range(900000): # nothing happens for these datapoints
del firstColumn[j]
del secondColumn[j]
del thirdColumn[j]
您可以通過執行以下操作跳過初始行:
with open(readFile, 'r') as f:
# skip first 900,000 lines
for _ in range(900000):
next(f)
for line in f:
parts = line.strip('\n').split(',')
firstColumn.append(parts[0])
secondColumn.append(parts[1])
thirdColumn.append(parts[2])
你是對的; 太可怕了。 轉換您不打算使用的 900K 行輸入是愚蠢的。 相反,完全跳過它們:
# read past first 900K lines
with open(readFile,'r') as readFile:
for _ in range(900000):
readFile.readline()
for eachline in readFile: # converting columns to lists
# Continue as before
完成后,我強烈建議您切換到 csv 閱讀器以獲取文件的 rest; 您可以從那里通過簡單的操作構建您的數據框。 請注意不要關閉並重新打開文件,或以其他方式重置文件 header 信息。
您可以使用 pandas 可以制作副本。csv 文件在副本中刪除了這些行。 首先制作文件的 dataframe,然后您可以使用 .iloc[] 將行索引放入您想要開始的位置。 這將在您要剪切的行之后。 像字符串一樣解析它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.