gpt4 book ai didi

python - CSV 文件行递增

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:18 24 4
gpt4 key购买 nike

目前我正在开发一个 CSV 文件程序,我必须将 CSV 文件分区为不重叠的部分(按行),但不应在磁盘中创建任何额外的文件。

目前我正在使用此程序按行读取 CSV 文件的特定部分:

def dataFromFile(fname):
record = []
count=0
with open(fname, 'rb') as f:
reader = csv.reader(f)
for row in reader:
while '' in row:
row.remove('')
count+=1
record.append(row)
print count
return record[0:4]

这里我能够读取 0-4 范围内的行。但是是否有可能自动执行此操作,即我们是否可以在每次读取接下来的 4 行等等直到 CSV 文件末尾时手动给出该范围?

CSV 文件包含:

apple   beer    rice    chicken
apple beer rice
apple beer
apple mango
milk beer rice chicken
milk beer rice
milk beer
milk mango

最佳答案

您可以使用yield :

def dataFromFile(fname):
record = []
print'Opening the file is executed once'
count = 0
with open(fname) as f:
for row in csv.reader(f, delimiter=' '):
count += 1
fields = [field for field in row if field]
if fields:
record.append(fields)
if len(record) == 4:
print 'Last yielded row:', count
yield(record)
record = []
if record:
yield record

以及调用:

for row in dataFromFile('your.csv'):
print row

来自口译员

>>> import csv
>>>
>>> def dataFromFile(fname):
record = []
print 'Opening the file is executed once'
count = 0
with open(fname) as f:
for row in csv.reader(f, delimiter=' '):
count += 1

fields = [field for field in row if field]
if fields:
record.append(fields)
if len(record) == 4:
print 'Last yielded row:', count
yield(record)
record = []
if record:
yield record
...
>>> for row in dataFromFile('your.csv'):
... print row
...
Opening the file is executed once
Last yielded row: 4
[['apple', 'beer', 'rice', 'chicken'], ['apple', 'beer', 'rice'], ['apple', 'beer'], ['apple', 'mango']]
Last yielded row: 8
[['milk', 'beer', 'rice', 'chicken'], ['milk', 'beer', 'rice'], ['milk', 'beer'], ['milk', 'mango']]
>>>

关于python - CSV 文件行递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com