Reputation: 21
I suppose that is a very simple question, but no for me until now... I have a file with the columns like this:
1 2 3 4 5 3
6 7 -8 9 0 5
4 8 -4 6 -7 8
and I have this code in python:
import csv
MyValues = [] #create an empty list
values = csv.reader(open('myfile', 'rb'), delimiter=' ')
for row in values:
MyValues.append(row[5] if len(row)>4 else None)
print MyValues
The problem is that the delimiter is not only a space, sometimes is two or 3 spaces. Until now I could not fix, even using sniffer or dialect routines... Someone have any idea how can I import the columns?
Upvotes: 2
Views: 1540
Reputation: 208525
Instead of using the csv module, just use str.split()
on each line:
MyValues = []
for line in open('myfile'):
row = line.split()
MyValues.append(row[5] if len(row)>4 else None)
print MyValues
str.split()
splits the string on whitespace by default, and consecutive whitespace characters will be treated as a single delimiter.
Upvotes: 6