[英]Selectively copy files from one folder directory to another
我有一個目錄樹,其中文件夾的名稱很重要。 我也有一個csv說從folder1> folder2> folder3> foo.txt。 folder1,folder2,folder3和txt都位於csv的不同列中。 我需要保持目錄結構不變,並復制csv中給出的文件。
我正在嘗試的方法是復制目錄樹並編寫python代碼以刪除不需要的文件。 所以有很多循環,但是我在csv中有超過415,000行。
csv example:<br/>
pdf_no . folder1. folder2 . folder3. <br/> 1 . . abc. pqr. xyz.<br/>
這是csv的格式,借助python中的pandas dataframe提取列數據沒有問題。 最初,這是一個.dta文件,我.csv with pandas. So 'folder1' > 'folder 2' > 'folder 3' > 'pdf_no'.
將其轉換為.csv with pandas. So 'folder1' > 'folder 2' > 'folder 3' > 'pdf_no'.
.csv with pandas. So 'folder1' > 'folder 2' > 'folder 3' > 'pdf_no'.
“ pdf_no”。 列包含文件名,這是我們想要在給定文件夾中保持文件結構的數字。
因此,這會花費很多時間,每當我再次更改時,都會花費很多時間,我什至不知道它是否正確。
您需要shutil.copytree方法。 您可以執行以下操作:
也許您必須添加一個try...except
塊,以避免在目標文件已存在時出現OsError
,或者在復制新文件之前刪除目標文件。
pdf_no,folder1,folder2,folder3
1,abc,def,ghi
2,xyz,pqr,
3,abc,def,ghi
import csv
import os
import shutil
target_csv = 'selection.csv'
target_dir = 'selected_20190828/'
source_dir = 'original_directory/'
with open(target_csv) as f:
rows = csv.reader(f)
for line_no, row in enumerate(rows):
if line_no == 0: # Skip the first line because it's the title
continue
pdf_name = row[0] + '.pdf'
dir_path = os.path.join(*row[1:])
source = os.path.join(source_dir, dir_path, pdf_name)
if not os.path.isfile(source):
print('not exist: ', line_no, source)
continue
target = os.path.join(target_dir, dir_path)
os.makedirs(target)
shutil.copy2(source, target)
實際上您不需要pandas
,您所需要的只是
csv.reader
將csv文件讀入list
os.makedirs
創建文件夾(此方法類似於bash中的mkdir -p
) os.path.join
shutil.copy2
將文件復制到新文件夾 os.path.isfile
以確保原始文件存在 我已經測試了上面的代碼。 它應該正在工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.