-4

In this example.

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?
in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL- C to abort."
raw_input()

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

on line 8 to 9 can't I just write it like this?

indata = open(from_file, 'r')
dfundako
  • 8,022
  • 3
  • 18
  • 34

1 Answers1

2

Sorry, I realize I misunderstood your question. Updated my response.


According to the documentation 'r' is just the default value for the "mode". So these two lines are equivalent.

in_file = open(from_file)
in_file = open(from_file, 'r')

Each "mode" represents what you can do with the file you just opened. All the possible options described on the documentation are:

'r'     open for reading (default)
'w'     open for writing, truncating the file first
'x'     open for exclusive creation, failing if the file already exists
'a'     open for writing, appending to the end of the file if it exists
'b'     binary mode
't'     text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newlines mode (deprecated)

The modes b, t and + should be used in conjunction with other modes. (For example, r+b allows you to read and write to a file without truncating it, assuming it is a binary file.)

If you want to just get the text from the file, you can by just calling .read() straight away

indata = open(from_file).read()

Regarding my personal preference however, less lines doesn't necessarily mean better. Best practice is generally an approach that handles all the side effects of file handling (such as closing) like this:

with open(from_file) as in_file:
    indata = in_file.read()

This question here contains a good summary of people's thoughts on the topic.

SCB
  • 5,821
  • 1
  • 34
  • 43