如何使用Python检查文件内容,并将同一文件夹中的文件复制到新位置?我有Python 3.1,但也可以轻松移植到2.6。谢谢!
例如
import os,shutil
root="/home"
destination="/tmp"
directory = os.path.join(root,"mydir")
os.chdir(directory)
for file in os.listdir("."):
flag=""
#check contents of file ?
for line in open(file):
if "something" in line:
flag="found"
if flag=="found":
try:
# or use os.rename() on local
shutil.move(file,destination)
except Exception,e: print e
else:
print "success"
shutil.move(src, dst)¶
Recursively move a file or directory to another location.
If the destination is on the current filesystem, then simply use rename.
Otherwise, copy src (with copy2()) to the dst and then remove src.