1

While doing some Python tutorials, the author of the book asked for the following (opening a file and reading its content):

#we could do this in one line, how?
in_file = open(from_file)
indata = in_file.read()

How can I do this in one line?

Pang
  • 9,564
  • 146
  • 81
  • 122
  • 1
    Why do you want to do it in one line? And how do you want the data, one big block `indata = open(from_file).read()` or a list of lines `indata = list(open(from_file))` – AChampion Jan 06 '17 at 03:53
  • Any time you're opening a file, you should probably use a `with` block. Take a look at [this post](http://stackoverflow.com/a/3644618/4541045) for some explanation about why you want to be careful opening and closing files. – ti7 Jan 06 '17 at 03:59
  • @AChampion. thank you very useful. I do need the data as one big block (as you propose) Why? well to learn a more neat from of coding. Thank you – Claudio Nunez Jan 06 '17 at 03:59
  • One line isn't necessarily neater - the idiomatic approach would be `with open(from_file) as in_file: indata = in_file.read()` Read up about [`with` statements](https://docs.python.org/3.5/reference/datamodel.html#context-managers) – AChampion Jan 06 '17 at 04:02

1 Answers1

2

You can get all the contents of the file from a file handler by by simply extending what you have with your path and reading from it.

indata = open(from_file).read()

However, it's more obvious what's happening and easier to extend if you use a with block.

with open(from_file) as fh:  # start a file handler that will close itself!
    indata = fh.read()  # get all of the contents of in_file in one go as a string

Beyond that, you should protect your file opening and closing from IOErrors if (for example) your file path does not exist.

Finally, files are by default opened read-only and raise an error if you (or someone else later) attempts to write to it, which will safeguard data blocks. You can change this from 'r' to a variety of other options depending on your needs.

Here is a fairly complete example with the above concepts.

def get_file_contents(input_path):
    try:
        with open(input_path, 'r') as fh:
            return fh.read().strip()
    except IOError:
        return None
Community
  • 1
  • 1
ti7
  • 16,375
  • 6
  • 40
  • 68
  • 1
    `indata = None` isn't helpful, `indata` will have a value or an exception would be thrown - catch the exception if you can gracefully handle it and assign a default value to `indata` there. – AChampion Jan 06 '17 at 04:10
  • You are correct - half-written thoughts of try/exceptions that could be confusing - I'll remove it and create a full example – ti7 Jan 06 '17 at 04:11
  • 1
    Also `r` mode is the default, so an error would occur if someone tries to write to it with or without the explicit mode arg. – AChampion Jan 06 '17 at 04:13