[Tutor] striping whitespace from files

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Jul 11 00:46:59 CEST 2004


> >>> f1 = open("citrate.txt",'r')
> >>> f2 = f1.read()

This reads the entire file into f2

> >>> from string import strip, split
> >>> f2 = f1.readlines()

This reads an empty line since you are already at the end 
of the file. It overwrites all the data you previously read!
YOu probably want to go straight to the split/strip operation 
now... A list comprehension might be a useful construct 
to think about...

> >>> list = split(f2,'\n')

Using a builtin name(list is the conversion to list function) 
is a bad idea. Also you could use the more modern version:

lines = f2.split('\n')

But since the line is empty it will still have no effect.

> >>> for i in fstrings:
> f1strings = string.split([i])

This tries to split a list containing i, I'm not sure what 
you even expect here. I'm even less sure what will actually 
be happening!

> print f1strings
> 
> 
> 
> Traceback (most recent call last):
>   File "<pyshell#86>", line 2, in -toplevel-
>     f1strings = string.split([i])
>   File "C:\Python23\lib\string.py", line 121, in split
>     return s.split(sep, maxsplit)
> AttributeError: 'list' object has no attribute 'split'
> >>> 

The error being because of the list construct...

HTH,

Alan G.


More information about the Tutor mailing list