如何使用 python 检查文件的内容,然后从同一文件夹复制文件并将其移动到新位置?我有 Python 3.1,但我可以轻松移植到 2.6,谢谢!
问问题
6254 次
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 doc,则在 .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() 移动到另一个文件系统。
于 2010-02-12T02:06:29.053 回答
1
于 2010-02-12T01:46:28.530 回答