write() vs. writelines()

G

Gregory Petrosyan

My question is: why write(''.join(...)) works slowly than
writelines(...)? Here's the code:

import sys
import random

#try:
#import psyco
#psyco.full()
#except ImportError:
#pass


def encrypt(key, infile, outfile, bufsize=65536):
random.seed(key)
in_buf = infile.read(bufsize)
while in_buf:
outfile.write(''.join(chr(ord(char) ^ random.randint(0, 255))
for char in in_buf))
in_buf = infile.read(bufsize)


if __name__ == '__main__':
import time
key = int(sys.argv[1])
infile = open(sys.argv[2], 'rb')
outfile = open(sys.argv[3], 'wb')
t = time.time()
encrypt(key, infile, outfile)
print time.time() - t
 
F

Fredrik Lundh

Gregory said:
My question is: why write(''.join(...)) works slowly than
writelines(...)? Here's the code:

the first copies all the substring to a single string large enough to
hold all the data, before handing it over to the file object, while the
second just writes the substrings to the file object.

</F>
 
G

Gregory Petrosyan

Thanks for your reply. I understand this fact, but I wonder why
writelines() works slowly -- I think C code can be optimised to work
faster than Python one. Is it correct that writelines(...) is just a
shorthand for

for ch in ...:
file.write(ch)
?
 
M

Marc 'BlackJack' Rintsch

Thanks for your reply. I understand this fact, but I wonder why
writelines() works slowly -- I think C code can be optimised to work
faster than Python one. Is it correct that writelines(...) is just a
shorthand for

for ch in ...:
file.write(ch)
?

Depends on `...`. If it's a string then yes because a string is a
sequence of characters. But `writelines()` is ment for a sequence of
strings. It's the counterpart of `readlines()`. Then it's just a
shorthand for::

for line in lines:
file.write(line)

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,296
Messages
2,571,535
Members
48,281
Latest member
DaneLxa72

Latest Threads

Top