将特定子目录中的某些文件移动到新目录中

时间:2016-01-29 17:15:36

标签: python shell csv

如何将特定子目录(不是所有子目录)中的某些文件(不是所有文件)移动到新目录中?

需要移动的文件已列在CSV文件中,数量约为85,000。他们的绝对路径被提到过。所有文件都具有相同的扩展名,即.java。特定子目录的数量约为13,000个。

是否有Python脚本(首选)或Shell脚本来执行此操作?

N.B:我搜索的论坛返回了有关如何将所有文件从单个子目录中移动到新目录中的解决方案。他们在下面提到:

  1. https://www.daniweb.com/programming/software-development/threads/473187/copymove-all-sub-directories-from-a-folder-to-another-folder-using-python

  2. http://pythoncentral.io/how-to-copy-a-file-in-python-with-shutil/

  3. Filter directory when using shutil.copytree?

  4. https://unix.stackexchange.com/questions/207375/copy-certain-files-from-specified-subdirectories-into-a-separate-subdirectory

2 个答案:

答案 0 :(得分:0)

这样的事可能适合你:

import os
import csv

def move_file(old_file_path, new_directory):
    if not os.path.isdir(new_directory):
        os.mkdir(new_directory)
    base_name = os.path.basename(old_file_path)
    new_file_path = os.path.join(new_directory, base_name)
    os.rename(old_file_path, new_file_path)

def parse_csv_file(csv_path):
    csv_file = open(csv_path)
    csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')
    paths = list(csv_reader)
    csv_file.close()
    return paths

if __name__ == '__main__':
    old_file_paths = parse_csv_file('your_csv_path')
    for old_file_path in old_file_paths:
        move_file(old_file_path, 'your_new_directory')

这假设您的CSV文件仅包含以逗号分隔的路径,并且所有这些文件都存在。

答案 1 :(得分:0)

假设您的CSV文件如下所示:

if($stmt = $this->db->prepare("SELECT table_users.id AS user_id, table_users.email AS user_email, table_users.GUID as user_guid, "
        . "table_roles.slug AS role_slug, table_user_settings.username, table_users.id_roles, "
        . "table_users.first_name, table_users.last_name, table_users.mobile_number, table_users.phone_number, "
        . "table_users.address, table_users.city, table_users.state, table_users.zip_code, table_users.notes "
        . "FROM table_users "
        . "INNER JOIN table_roles ON table_roles.id = table_users.id_roles "
        . "INNER JOIN table_user_settings ON table_user_settings.GUID = table_user.GUID "
        . "WHERE table_users.data = 0 AND "
        . "WHERE table_user_settings.username = ? AND "
        . "WHERE table_user_settings.password = ? "))

您可以使用以下shell命令移动文件:

George,/home/geo/mtvernon.java,Betsy
Abe,/home/honest/gettys.java,Mary