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

3

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

2个回答

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 文档,在 .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()函数将文件移动到另一个文件系统中。

不要给人们带有“except Exception”的代码,这是一个漏洞。你没有提供对可能引发的大量异常(如“KeyboardInterrupt”)的合理响应。 - Mike Graham
1
在2.5中,Exception继承自BaseException。你认为它能捕获KeyboardInterrupt吗?OP有3.1和2.6。 - ghostdog74

1

1
它可以在文件系统中的任何位置移动文件,包括已挂载的网络驱动器。 - Ignacio Vazquez-Abrams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接