File input/output: Difference between revisions

→‎{{header|Python}}: Source to shutil.copyfile makes the other examples redumdant.
m (→‎{{header|Python}}: more robust version: `with`, "b", readline)
(→‎{{header|Python}}: Source to shutil.copyfile makes the other examples redumdant.)
Line 797:
=={{header|Python}}==
 
<python>x = open("output.txt","w")
y = open("input.txt","r")
x.write(y.read())
x.close()
y.close()</python>
 
or:
 
The following use of the standard libraries shutil.copyfile is to be preferred. (Current source code ensures a restricted buffer is used to copy the files using binary mode and any used file descriptors are always closed).
<python>import shutil
shutil.copyfile('input.txt', 'output.txt')</python>
 
or:
 
<python>from __future__ import with_statement # for versions < 2.6
 
# It works in presence of exceptions (files will be closed automatically)
# Read/write in binary mode to avoid text decoding/encoding.
with open("input.txt","rb") as input_:
with open("output.txt","wb") as out:
for line in input_: # slower, but requires less memory
out.write(line)
# or, just ``out.write(input_.read())`` if there is enough memory</python>
 
=={{header|RapidQ}}==
Anonymous user