簡體   English   中英

從CSV文件導出文件名列表並使用python復制到另一個目錄

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

我有一個包含文件列表的 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'])

這樣我可以打印文件的名稱。 你能幫我完成只復制列表文件的代碼嗎? 謝謝。 enter code here

問題是os.listdir()返回包含在您提供的目錄的文件列表- 在本例中為“C:\\test”。

稍后,當您嘗試將source與單個文件連接起來時,您將嘗試將列表與 str 組合起來。 這就是您收到TypeError

如果所有文件都直接包含在“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)

請注意,使用os.path.join()也是構建文件路徑的更好解決方案。

我用這段代碼解決了我的問題:

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