简体   繁体   中英

Python: copy file from a directory to another reading the layer columns

I have a table with two columns with links to directory and/or file and NULL Each record has a columns 'NAME' as name of new directory Something like this

...  NAME   HOTLINK1                  HOTLINK2
...  name1  C:\...\directory1         C:\...\directory6\file
...  name2  C:\...\directory2         NULL
...  name3  C:\...\directory5\file    C:\...\directory
...  name4  NULL                      NULL

I'm trying to write a code to copy the entire contents of the directory (subdirectories included) and the file from HOTLINK1 and HOTLINK2 to new directory 'NAME'.

So:

  • if HOTLINK is a directory >>> copy the entire contents of the directory (subdirectories included)

  • if HOtLINK is a file >>> copy the file

  • if is NULL >> pass.

You already have a pretty clear method in human language, maybe just need a few tips to write them in Python codes.

  1. How to read each row and the link columns, parsing strings by newlines and splitting by spaces should work.
  2. How to tell if a path is a file or a directory (or at least exists)? Try os.path module.
  3. How to copy file or folder? Try shutil module.
  4. Watch out for the backslash in file path of Windows system, it needs to be escaped.
import os
print(os.path.isdir("/home/el"))

result True or False

 print(os.path.exists("/home/el/myfile.txt"))

result True or False

import shutil
shutil.copytree('hotlink1', 'hotlink2')

Thanks to the suggestions of @ Dev Jalla and @ Neo X I have write this code that work. It used the values of one column HOTLINK1. Now I don't know to add the code to produce the same thing with values of HOTLINK2 whereas the folder calle 'NAME' already exists:

import shutil
    import csv
    import os

    source='D:\\Prova_copy_pyhton\\'
    with open('D:\\Prova_copy_pyhton\\list.csv') as csvfile:
           reader = csv.DictReader(csvfile, delimiter=';')
           for row in reader:

               a = row['hotlink1']
               fa= os.path.basename(a)
               out = row['name']

               if os.path.isdir(a):
                 shutil.copytree(a, os.path.join(source, out))

               elif os.path.exists(a):
                    try:
                       os.stat(os.path.join(source, out))
                    except:
                        os.mkdir(os.path.join(source, out))
                        shutil.copy(a, source+out+'\\'+fa)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM