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

3 投票
2 回答
7342 浏览
提问于 2025-04-15 19:11

你想知道怎么用Python检查一个文件的内容,然后从同一个文件夹里复制一个文件并把它移动到新的地方吗?我现在用的是Python 3.1,但我也可以很容易地换成2.6版本。谢谢!

2 个回答

1

os.listdir() 是一个用来列出文件夹里所有文件和子文件夹的函数。简单来说,它可以帮你查看某个文件夹里面都有什么东西。

shutil.move() 是一个用来移动文件或文件夹的函数。也就是说,如果你想把一个文件从一个地方搬到另一个地方,就可以用这个函数来完成。

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() 来移动到另一个文件系统。

撰写回答