Searching files in directories

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • pkilambi@gmail.com

    #1

    Searching files in directories

    can anyone help me with this...

    I want to search for a list for files in a given directory and if it
    exists copy them to destination directory

    so what i am looking for is :

    file = 'file1.txt'
    source_director y = '/tmp/source/'
    destination_dir ectory = '/tmp/destination/'

    so If the file exists in source_director y cp that file to the
    destination_dir ectory..

    hope I am clear

  • Larry Bates

    #2
    Re: Searching files in directories

    Not tested but should be close:

    import os
    import shutil

    files = ['file1.txt']
    source_director y = '/tmp/source/'
    destination_dir ectory = '/tmp/destination/'

    for file in files:
    src=os.path.joi n(source_direct ory, file
    dst=os.path.joi n(destination_d irectory, file
    if os.path.exists( os.path.join(so urce_directory, file):
    shutil.copy(src , dst)

    -Larry Bates

    pkilambi@gmail. com wrote:[color=blue]
    > can anyone help me with this...
    >
    > I want to search for a list for files in a given directory and if it
    > exists copy them to destination directory
    >
    > so what i am looking for is :
    >
    > file = 'file1.txt'
    > source_director y = '/tmp/source/'
    > destination_dir ectory = '/tmp/destination/'
    >
    > so If the file exists in source_director y cp that file to the
    > destination_dir ectory..
    >
    > hope I am clear
    >[/color]

    Comment

    • George Sakkis

      #3
      Re: Searching files in directories

      "Larry Bates" wrote:
      [color=blue]
      > Not tested but should be close:
      >
      > import os
      > import shutil
      >
      > files = ['file1.txt']
      > source_director y = '/tmp/source/'
      > destination_dir ectory = '/tmp/destination/'
      >
      > for file in files:
      > src=os.path.joi n(source_direct ory, file
      > dst=os.path.joi n(destination_d irectory, file
      > if os.path.exists( os.path.join(so urce_directory, file):
      > shutil.copy(src , dst)[/color]


      Or more succinctly using the path module:

      from path import path

      files = ['file1.txt']
      src_dir = path('/tmp/source/')
      dest_dir = path('/tmp/destination/')

      for filename in files:
      srcfile = src_dir / filename
      if srcfile.exists( ):
      srcfile.copy(de st_dir)


      George

      Comment

      Working...