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

发布于 2024-08-21 10:00:52 字数 82 浏览 2 评论 0原文

如何使用 python 检查文件的内容,然后从同一文件夹复制文件并将其移动到新位置? 我有 Python 3.1,但我可以轻松移植到 2.6 谢谢你!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独享拥抱 2024-08-28 10:00:52

例如,

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

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.

北笙凉宸 2024-08-28 10:00:52

os.listdir() 和 < a href="http://docs.python.org/library/shutil.html#shutil.move" rel="nofollow noreferrer">shutil.move()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文