Python Idioms
目录

Accessing the index in Python for loops

for idx, val in enumerate(ints):
print idx, val

Merge two Python dictionaries

z = x.copy()
z.update(y)

string contains

if not "blah" in somestring: continue
if "blah" not in somestring: continue

list files in a directory

# 1
from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

# 2
from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)
break

# 3
import glob
print glob.glob("/home/adam/*.txt")

check EOF when read

# file not changed since read
f.tell() == os.fstat(f.fileno()).st_size

发表评论