繁体   English   中英

有选择地将文件从一个文件夹目录复制到另一个文件夹

[英]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方法。 您可以执行以下操作:

  1. 阅读您的CSV
  2. 构建文件路径(使用os.path.join())
  3. 使用shutil.copytree将文件及其父目录复制到目标

也许您必须添加一个try...except块,以避免在目标文件已存在时出现OsError ,或者在复制新文件之前删除目标文件。

样本csv

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.

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