简体   繁体   English

从CSV文件导出文件名列表并使用python复制到另一个目录

[英]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 :我有一个包含文件列表的 csv 文件: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips 我想用 python 创建一个脚本,用于将此文件列表从一个目录复制到另一个目录,我可以这样做:

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".问题是os.listdir()返回包含在您提供的目录的文件列表- 在本例中为“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.稍后,当您尝试将source与单个文件连接起来时,您将尝试将列表与 str 组合起来。 This is why you are getting the TypeError .这就是您收到TypeError

If all of the files are contained directly in "C:\\test", then you can drop the os.listdir() and do:如果所有文件都直接包含在“C:\\test”中,那么您可以删除os.listdir()并执行以下操作:

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.请注意,使用os.path.join()也是构建文件路径的更好解决方案。

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'])) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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