Delete spaces

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Sep 28 11:55:48 EDT 2007


koutoo at hotmail.com a écrit :
> If I have a text file that is delimited by spaces,

spaces or tabs ?

> how do I import it
> and get to comma delimited?  Here is a row of data from the text file:
> 
> 1    1    10:55:14  2    65   8.5
> 1.4+1.1                       2.5       Class-2   0


> I tried a few examples from the group and it didn't work, since the
> file also has a header row and a row of seperators ( -------).  The
> lengths of each row is something like 130, so there are extra spaces
> after the last value as well.  I have tried joining and other things,
> but I couldn't figure out how to get the values to come together.
> Thanks.

This should answer your question - but certainly not solve your problem 
(cf below):

f = open('/path/to/file.txt');
file.readline(); # skip headers
for line in f:
   # skip separators
   if line.startswith('---'):
     continue
   parts = filter(line.rstrip().split())
   print ';'.join(parts)

f.close()


Now the problem is that, obviously, the position of a group of data in a 
line is meaningfull, so just filtering out spaces isn't the solution. 
Did you check that it's not really a tab-delimited file ? If yes, doing 
line.split('\t') might help. Or just trying with the csv module FWIW.

My 2 cents...



More information about the Python-list mailing list