I want to have a function that writes data to a file:
def data_writer(data, file_name):
spiffy_data = data # ...
with open(file_name, 'w') as out:
out.write(spiffy_data)
But sometimes, I have a file object instead of a file name. In this case, I sometimes have a tempfile.TemporaryFile
(which creates a file-like object that's writable).
I'd like to be able to write something like:
def data_writer(data, file_thing):
spiffy_data = data # ...
if type(file_thing) is file_like:
file_thing.write(spiffy_data)
else:
with open(file_name, 'w') as out:
out.write(spiffy_data)
What's a good way to do this?
Also, does makes sense to do in Python?
A function should do one thing, and do that one thing well. In the case of data_writer
, its one thing is to write data to a file-like object. Let the caller worry about providing such an object. That said, you can also provide that caller in the form of a wrapper that takes a file name and opens it for data_writer
.
def data_writer(data, file_obj):
spiffy_data = data # ...
file_obj.write(spiffy_data)
def write_data_to_file(data, file_name):
with open(file_name, "w") as f:
data_writer(f, file_name)
While your approach is LBYL
, it's pythonic to assume it's EAFP
. So you could just try
to
write()
to the file_thing
you received or open()
it and except
a potential exception, depending on which you feel better represents the default case.
Edit: Cf ShadowRanger's comment for why mixing the exception handling with a context manager is rather unelegant here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.