[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.

John

-----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')
out.writelines(inf)
out.close()
inf.close()

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




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


_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list