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

Time:12-05

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related