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?
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?
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