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!
can shutil.move() move files across the network?
Morpheous
2010-02-12 02:00:40
It can move files anywhere across the filesystem, including mounted network drives.
Ignacio Vazquez-Abrams
2010-02-12 02:01:49
+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
2010-02-12 02:06:29
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
2010-02-12 02:15:25
In 2.5, Exception inherits from BaseException. do you think it will catch KeyboardInterrupt? OP has 3.1 and 2.6.
ghostdog74
2010-02-12 02:35:16