如何使用Python检查文件夹的内容

时间:2010-02-12 01:44:36

标签: python directory cpython

如何使用python检查文件的内容,然后从同一文件夹中复制文件并将其移动到新位置? 我有Python 3.1,但我可以轻松地移植到2.6 谢谢!

2 个答案:

答案 0 :(得分:3)

例如

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 doc,请在.move()下面显示

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.

我猜你可以使用copy2()移动到另一个文件系统。

答案 1 :(得分:1)