File Reading related query
Tim Chase
python.list at tim.thechases.com
Wed Sep 17 06:52:07 EDT 2008
> I am talking about text file which contain multiple lines e.g following
> three lines are there in my textfile.txt
>
> this is python list
> where we get support
> from geeks
>
> I want
>
> sentence = this is python list where we get support from geeks
>
> whereas when i use simple read() i get something like this
>
> sentence = this is python list\nwhere we get support\nfrom geeks
You mean
sentence = myfile.read().replace('\n', ' ')
?
If you want to compact multiple spaces, such as
this is the python__
list where__
__we get support
(where "_" represents a space) and you want that to become
this is the python list where we get support
you'd have to use slightly more intelligent processing, and
explain the behavior you'd want if more than one blank line was
encountered. But for a first pass:
import re
r = re.compile(r"\s*\n")
sentence = r.sub(" ", myfile.read())
-tkc
More information about the Python-list
mailing list