Writelines() a bit confusing

Stefan Sonnenberg-Carstens stefan.sonnenberg at pythonmeister.com
Sat May 19 09:31:50 EDT 2007


aiwarrior schrieb:
> If file.WriteLines( seq ) accepts a list and it says it writes lines,
> why does it write the whole list in a single line. Be cause of that
> the reverse of file.writelines(seq) is not file.readlines().
> Are the assumptions i made correct? If yes why is this so?
>
> I find a function called writelines not actualy writing the list in
> lines wierd.
>
> [code]
> something = ['re','ri','ro']
> f.writelines( something )
> something_else = f.readlines()
> [/code]
> In this case the list something_else will be diffrent from something
>
>   
Please see this:
 >>> help(f.writelines)
Help on built-in function writelines:

writelines(...)
    writelines(sequence_of_strings) -> None.  Write the strings to the file.
   
    Note that newlines are not added.  The sequence can be any iterable 
object
    producing strings. This is equivalent to calling write() for each 
string.

so you'd want this:

f.writelines([x+os.linesep for x in strings])

or something similar.

Why ? Ask the originator of this function.
One explanation:
If you do this:

f1 = file('file1')
f2 = file('file2','w')
f2.writelines(f1.readlines())
f1.close() ; f2.close()

all is how it should be.



More information about the Python-list mailing list