Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the file content by space and end-of-line character?

When I do the following list comprehension I end up with nested lists:

channel_values = [x for x in [ y.split(' ') for y in
    open(channel_output_file).readlines() ] if x and not x == '\n']

Basically I have a file composed of this:

7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615
8626 8623 8620 8617 8614 8610 8607 8604 8600 8597 8594 8597 8594 4444
<snip several thousand lines>

Where each line of this file is terminated by a new line.

Basically I need to add each number (they are all separated by a single space) into a list.

Is there a better way to do this via list comprehension?

like image 295
UberJumper Avatar asked Sep 10 '25 07:09

UberJumper


2 Answers

You don't need list comprehensions for this:

channel_values = open(channel_output_file).read().split()
like image 157
Lukáš Lalinský Avatar answered Sep 12 '25 20:09

Lukáš Lalinský


Just do this:

channel_values = open(channel_output_file).read().split()

split() will split according to whitespace that includes ' ' '\t' and '\n'. It will split all the values into one list.

If you want integer values you can do:

channel_values = map(int, open(channel_output_file).read().split())

or with list comprehensions:

channel_values = [int(x) for x in open(channel_output_file).read().split()]
like image 38
Nadia Alramli Avatar answered Sep 12 '25 22:09

Nadia Alramli