Skip to content

Instantly share code, notes, and snippets.

@arne-cl
Created January 3, 2021 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arne-cl/e20357042bf87d02638d8bab3780cdc6 to your computer and use it in GitHub Desktop.
Save arne-cl/e20357042bf87d02638d8bab3780cdc6 to your computer and use it in GitHub Desktop.
Python3: write to file if filename is given as argument, else write to stdout.
import argparse
import datetime
import sys
"""
This script writes the current timestamp to the file given a cli argument.
If no filename is given, the timestamp is written to stdout.
"""
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('output_file', nargs='?', default=sys.stdout)
args = parser.parse_args()
timestamp = datetime.datetime.now()
if isinstance(args.output_file, str): # write to file
with open(args.output_file, 'w') as output_file:
print(timestamp, file=output_file)
else: # write to STDOUT
print(timestamp, file=args.output_file)
@arne-cl
Copy link
Author

arne-cl commented Jan 5, 2021

Caveat: print(some_string, file=output_file) appends a newline at the end of the file!
Alternative: use output_file.write(some_string)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment