简体   繁体   中英

Export the list of file name from CSV file and copy to another directory with python

i have one csv file that include the list of file: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips I would like to create one script with python for copy this list of file from one directory to another directory, i can do this :

import csv
import os
import shutil
source = os.listdir("C:\Test")
destination = "C:\Test1"
with open('semplice1.csv') as csvfile:
       reader = csv.DictReader(csvfile)
       for row in reader:
           print(row['nome'])

in this wway i can print the name of the file. Can you help me to complete the code for copy only the list file? Thanks. enter code here

The issue is that os.listdir() returns a list of files contained in the directory that you give it - in this case "C:\\test".

Later on, when you then try and concatenate source with the individual files, you are therefor attempting to combine a list with a str. This is why you are getting the TypeError .

If all of the files are contained directly in "C:\\test", then you can drop the os.listdir() and do:

import csv
import os
import shutil

source = "C:\Test"
destination = "C:\Test1"

with open('semplice1.csv') as csvfile:
       reader = csv.DictReader(csvfile)
       for row in reader:
           print(row['nome'])
           a = row['nome']
           shutil.copyfile(os.path.join(source, a), destination)

Note the use of os.path.join() also as a better solution for building filepaths up.

I resolve my problem with this code:

import csv
import os
import shutil

source = "C:\Test"
destination = "C:\Test1"

with open('semplice1.csv') as csvfile:
       reader = csv.DictReader(csvfile)
       for row in reader:
           print(row['nome'])
           shutil.copyfile(os.path.join(source, row['nome']), os.path.join(destination, row['nome'])) 

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