开发者

How to check contents of a folder using Python

开发者 https://www.devze.com 2022-12-20 02:54 出处:网络
How can you check the cont开发者_开发知识库ents of a file with python, and then copy a file from the same folder and move it to a new location?

How can you check the cont开发者_开发知识库ents of a file with python, and then copy a file from the same folder and move it to a new location? I have Python 3.1 but i can just as easily port to 2.6 thank you!


for example

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"

If you look at the shutil doc, under .move() it says

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.

I guess you can use copy2() to move to another file system.


os.listdir() and shutil.move().

0

精彩评论

暂无评论...
验证码 换一张
取 消