##// END OF EJS Templates
add '-a' for amending to %%file
MinRK -
Show More
@@ -682,7 +682,11 b' class OSMagics(Magics):'
682 @magic_arguments.magic_arguments()
682 @magic_arguments.magic_arguments()
683 @magic_arguments.argument(
683 @magic_arguments.argument(
684 '-f', '--force', action='store_true', default=False,
684 '-f', '--force', action='store_true', default=False,
685 help='Whether to overwrite a file if it already exists'
685 help='Force overwrite without prompting'
686 )
687 @magic_arguments.argument(
688 '-a', '--amend', action='store_true', default=False,
689 help='Open file for amending if it exists'
686 )
690 )
687 @magic_arguments.argument(
691 @magic_arguments.argument(
688 'filename', type=unicode,
692 'filename', type=unicode,
@@ -690,36 +694,35 b' class OSMagics(Magics):'
690 )
694 )
691 @cell_magic
695 @cell_magic
692 def file(self, line, cell):
696 def file(self, line, cell):
693 """Write a cell to a file
697 """Write the contents of the cell to a file.
694
695 %%file [-f] filename
696
697 Writes the contents of the cell to a file.
698
698
699 Will not overwrite existing files unless `-f` is specified.
699 For frontends that do not support stdin (Notebook), -f is implied.
700 """
700 """
701 args = magic_arguments.parse_argstring(self.file, line)
701 args = magic_arguments.parse_argstring(self.file, line)
702 args.filename = unquote_filename(args.filename)
702 args.filename = unquote_filename(args.filename)
703 force = args.force
703 force = args.force
704
704
705 if os.path.exists(args.filename):
705 if os.path.exists(args.filename):
706 if not force:
706 if args.amend:
707 try:
707 print "Amending to %s" % args.filename
708 force = self.shell.ask_yes_no(
708 else:
709 "%s exists, overwrite (y/[n])?",
709 if not force:
710 default='n'
710 try:
711 )
711 force = self.shell.ask_yes_no(
712 except StdinNotImplementedError:
712 "%s exists, overwrite (y/[n])?",
713 force = True
713 default='n'
714 )
715 except StdinNotImplementedError:
716 force = True
714
717
715 if not force:
718 if not force:
716 # prompted, but still no
719 # prompted, but still no
717 print "Force overwrite with %%file -f " + args.filename
720 print "Force overwrite with %%file -f " + args.filename
718 return
721 return
719
722 print "Overwriting %s" % args.filename
720 print("Overwriting %s" % args.filename)
721 else:
723 else:
722 print("Writing %s" % args.filename)
724 print "Writing %s" % args.filename
723
725
724 with io.open(args.filename, 'w', encoding='utf-8') as f:
726 mode = 'a' if args.amend else 'w'
727 with io.open(args.filename, mode, encoding='utf-8') as f:
725 f.write(cell)
728 f.write(cell)
General Comments 0
You need to be logged in to leave comments. Login now