views:

76

answers:

2

How can you check the contents 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!

+1  A: 

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

Ignacio Vazquez-Abrams
can shutil.move() move files across the network?
Morpheous
It can move files anywhere across the filesystem, including mounted network drives.
Ignacio Vazquez-Abrams
+2  A: 

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.

ghostdog74
Don't give people code with `except Exception`, which is a bug. You do not provide a reasonable response to lots of exceptions that could be raised, such as `KeyboardInterrupt`.
Mike Graham
In 2.5, Exception inherits from BaseException. do you think it will catch KeyboardInterrupt? OP has 3.1 and 2.6.
ghostdog74