读取文本或CSV文件并分成由空格分隔的组

0yg35tkg  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(162)

我有一个.csv文件,其中的数据为:

20
40
25

50
60
80

10
25
34
75
50

50
60

我需要读取此文件,并在发现空值时创建数字组。因此,对于上面的示例,它应该变为:

final_list = [
    [20, 40, 25],
    [50, 60, 80],
    [10, 25, 34, 75, 50],
    [50, 60]
]
qoefvg9y

qoefvg9y1#

只要一行一行地读取csv文件&列表中的多个空字符串,就可以像这样使用itertools.groupby

from itertools import groupby
with open(r"codeMaster.csv") as fp:
    line = fp.readlines()

line = [i.strip() for i in line]

print([list(g) for k, g in groupby(line, key=bool) if k])

给出编号

[['20', '40', '25'], ['50', '60', '80'], ['10', '25', '34', '75', '50'], ['50', '60']]

更多的Python##

with open(r"CodeMaster.csv") as fp:
    line = fp.readlines()

line = [i.strip() for i in line]
result = [[]]
for i in line:
    if not i:
        result.append([])
    else:
        result[-1].append(i)
print(result)

还提供#

[['20', '40', '25'], ['50', '60', '80'], ['10', '25', '34', '75', '50'], ['50', '60']]
dz6r00yl

dz6r00yl2#

若要读取.csv文件并将其分成由空格分隔的组,可以使用以下代码:

import csv

final_list = []
with open('filename.csv') as file:
  reader = csv.reader(file)
  temp_list = []
  for row in reader:
    if not row:
      final_list.append(temp_list)
      temp_list = []
    else:
      temp_list.append(row)
  final_list.append(temp_list)

print(final_list)

相关问题