Skip to content

Instantly share code, notes, and snippets.

@szeitlin
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save szeitlin/4d0e3ee52cef1b369d63 to your computer and use it in GitHub Desktop.

Select an option

Save szeitlin/4d0e3ee52cef1b369d63 to your computer and use it in GitHub Desktop.
nbpyfile_cleaner
__author__ = 'szeitlin'
#script to remove # In[1]: etc. from IPython notebook exported files
#import os
import re
#import sys
def nb_cleaner(nbpyfile, nonnbfile="newfile.py"):
'''
Helper function for converting python files exported from IPython notebooks into actual programs.
Takes an IPython notebook exported 'python' file, and a new file name.
These files suffer from retaining useless codecells throughout, designated as "# In[1]:".
Iterates through the file exported from the notebook, compares to regex and skips lines we don't want,
copying everything else to a new file.
:return: cleaner copy of the file.
'''
with open(nbpyfile, 'r') as old_file:
p = re.compile("^# In")
for line in old_file:
if p.match(line):
continue
else:
with open(nonnbfile, 'a') as new_file:
new_file.write(str(line))
return
#nbpyfile = "bike1year_viz2.py"
nb_cleaner(nbpyfile, nonnbfile)
@szeitlin
Copy link
Copy Markdown
Author

Helper function for converting python files exported from IPython notebooks into actual programs.

Takes an IPython notebook exported 'python' file, and a new file name.
Removes useless codecells throughout, designated as "# In[1]:"
Returns a cleaner copy of the python file. 

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