Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check contents of a folder using Python

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!

like image 674
Gabe Avatar asked Oct 24 '25 10:10

Gabe


2 Answers

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.

like image 143
ghostdog74 Avatar answered Oct 26 '25 01:10

ghostdog74


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

like image 30
Ignacio Vazquez-Abrams Avatar answered Oct 26 '25 00:10

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!