Skip to content

Instantly share code, notes, and snippets.

@terryoy
Last active December 11, 2015 07:18
Show Gist options
  • Save terryoy/4564968 to your computer and use it in GitHub Desktop.
Save terryoy/4564968 to your computer and use it in GitHub Desktop.
Python Script Collections
### get command history in interactive environment ###
import readline
for i in range(readline.get_current_history_length()):
print readline.get_history_item(i)
### find string patterns in text file ###
f = open('some.txt')
text = f.read()
f.close()
import re
re.findall('src="\S+"', text) # ref http://docs.python.org/2/howto/regex.html
### filtering a list ###
imgFiles = [i.split('/')[-1] for i in imgLinks if i.startwith('http')] # get the file names of the images with full links in the list
### exporting list to plain text file ###
outfile = open('plain.txt', 'w')
outfile.writelines("%s\n" % s for s in str_list)
outfile.close()
### exporting list to json string
import json
json.dumps(items) # one line contains all
json.dumps(items, indent=4) # pretty-printed
## to file
json.dump(items, items_json) # notice the "dump" without "s"
json.dump(items, items_json, indent=2) # pretty-printed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment