kensuke1984
kensuke1984

Reputation: 995

Python3 how to read a file delimited by spaces which length varies

I would like to make a Python3 code using csv.reader.

This is an example file to read.

#hoge.txt
a b c d  e f    g
a    b c d  e   f    g
a b c   d  e f    g
a  b   c   d e    f  g

I want to have arrays like this

[[a,a,a,a],[b,b,b,b],[c,c,c,c]...[g,g,g,g]]

(The number of elements is fixed.)

My current code is

from csv import reader
with open('hoge.txt') as f:
    data = reader(f, delimiter=' ')

But, apparently, it doesn't work. How can I make it as if

    data = reader(f, delimiter='\s+')

Upvotes: 0

Views: 52

Answers (2)

Amit Gupta
Amit Gupta

Reputation: 2938

with open('hoge.txt', 'r') as fin:
    data=[line.split() for line in fin]

this will give the output like

[['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 
['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd', 'e', 'f', 'g']]

but since your desired output is different so

list1 = []
for i in range(0,len(data)):
    list1.append([x[i] for x in data])

this will produce

[['a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b'], ['c', 'c', 'c', 'c'], ['d', 'd', 'd', 'd']]

I hope it solves your issue.

Upvotes: 3

James McPherson
James McPherson

Reputation: 2576

Are you sure you've got CSV? Your example file is space-delimited, and my first approach is to use split(). Something like this:

allcols = []
with open("hoge.txt", "r") as f:
    vals = f.read().split()
    for i, el in enumerate(vals):
        allcols[i].append(el)

If you really do have CSV but with extraneous spaces, then I'd still go with per-line processing, but like this:

from csv import reader
data = ""
with open("hoge.txt", "r") as f:
    newline = f.read().strip(" ")
    data.append(reader(newline))

hth

Upvotes: 1

Related Questions