[Tutor] write a file

John Purser johnp at HomeLumber.com
Wed Mar 24 15:05:50 EST 2004

Thanks Karl.  I hadn't seen writelines() before.


-----Original Message-----
From: Karl Pflästerer [mailto:sigurd at 12move.de]
Sent: Wednesday, March 24, 2004 12:53 PM
To: tutor at python.org
Subject: Re: [Tutor] write a file

On 24 Mar 2004, APQ LE <- apqle75 at hotmail.com wrote:

> I'm trying to open a file, read its content and write its content to a
> new file.  Pretty much like copying a file.  Here is what I have

> ========
> in = open ("a.txt", "r")
> out = open ("b.txt", "w")
> for line in in.readlines()
>    out.write(line)

> in.close()
> out.close()

> ==========
> However, the output isn't as expected.  There is additional empty line
> comes after every existing line.  So, the output file is bigger than
> the original file.

What OS are you working on?

Furthermore the above code is overcomplicated; I assume you use a recent
version of Python.  Then you could write:

inf = file('a.txt')
out = file('b.txt', 'w')

writelines() takes an iterator as argument: here the open file object.

Please do *not* send copies of replies to me.
I read the list

Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list