Read text or CSV file and break into groups separated by space

Question:

I have a .csv file with data as:

20
40
25

50
60
80

10
25
34
75
50

50
60

I need to read this file and create groups of numbers whenever a blank value is found. Hence, for the example above, it should become:

final_list = [
    [20, 40, 25],
    [50, 60, 80],
    [10, 25, 34, 75, 50],
    [50, 60]
]
Asked By: CodeMaster

||

Answers:

To read a .csv file and break it into groups separated by space, you can use the following code:

# Import the necessary libraries
import csv

# Initialize the final list
final_list = []

# Open the .csv file using the open() method
with open('filename.csv') as file:
  # Read the .csv file using the csv.reader() method
  reader = csv.reader(file)
  # Initialize a temporary list
  temp_list = []
  # Iterate over the rows of the .csv file
  for row in reader:
    # If the row is empty, append the temporary list to the final list and 
    # reset the temporary list
    if not row:
      final_list.append(temp_list)
      temp_list = []
    # If the row is not empty, append it to the temporary list
    else:
      temp_list.append(row)
  # Add the last temporary list to the final list
  final_list.append(temp_list)

# Print the final list
print(final_list)
Answered By: simeon2941

Just read a csv file line by by line & than one blank string in the list, you can use itertools.groupby like this:

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])

Gives #

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

More pythonic ##

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)

Also Gives #

[['20', '40', '25'], ['50', '60', '80'], ['10', '25', '34', '75', '50'], ['50', '60']]
Answered By: Bhargav
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.