繁体   English   中英

如何每次从 python 或 pyspark 中的 csv 读取 10 条记录?

[英]how to read 10 records every time from csv in python or pyspark?

我有一个包含 100,000 行的 csv 文件,我想一次读取 10 行并处理每一行以每次保存到其各自的文件并休眠 5 秒。 我正在尝试 Nslice,但它只读取前 10 个并停止。 我希望程序运行到 EOF。 如果有任何帮助,我正在使用 jupyter、python2 和 pyspark。

from itertools import islice
with open("per-vehicle-records-2020-01-31.csv") as f:
    while True:
        next_n_lines = list(islice(f, 10))
        if not next_n_lines:
            break
        else:
            print(next_n_lines)
            sleep(5)

这不会分隔每一行。 它将 10 行组合成一个列表

['"cosit","year","month","day","hour","minute","second","millisecond","minuteofday","lane","lanename","straddlelane","straddlelanename","class","classname","length","headway","gap","speed","weight","temperature","duration","validitycode","numberofaxles","axleweights","axlespacings"\n', '"000000000997","2020","1","31","1","30","2","0","90","1","Test1","0","","5","HGV_RIG","11.4","2.88","3.24","70.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","3","0","90","2","Test2","0","","2","CAR","5.2","3.17","2.92","71.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","5","0","90","1","Test1","0","","2","CAR","5.1","2.85","2.51","70.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","6","0","90","2","Test2","0","","2","CAR","5.1","3.0","2.94","69.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","9","0","90","1","Test1","0","","5","HGV_RIG","11.5","3.45","3.74","70.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","10","0","90","2","Test2","0","","2","CAR","5.4","3.32","3.43","71.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","13","0","90","2","Test2","0","","2","CAR","5.3","3.19","3.23","71.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","13","0","90","1","Test1","0","","2","CAR","5.2","3.45","3.21","70.0","0.0","0.0","0","0","0","",""\n', '"000000000997","2020","1","31","1","30","16","0","90","1","Test1","0","","5","HGV_RIG","11.0","2.9","3.13","69.0","0.0","0.0","0","0","0","",""\n']

这应该有效:

import pandas as pd
import time
path_data = 'per-vehicle-records-2020-01-31.csv'

reader = pd.read_csv(path_data, sep=';', chunksize=10, iterator=True)
for i in reader:
    df = next(reader)
    print(df)
    time.sleep(5) 

chunksize 将每 10 行读取一次,for 循环应确保以这种方式读取它们,并在每次迭代之间休眠 5 秒。

islice 重新运行生成器,因此您需要在分配它后进行迭代

from itertools import islice
with open("per-vehicle-records-2020-01-31.csv") as f:
    while True:
        next_n_lines = islice(f, 10)
        if not next_n_lines:
            break
        else:
            for line in next_n_lines:
               print(line)
            sleep(5)

你在这里阅读更多如何在 Python 中一次读取 N 行文件?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM