将特定文件从特定子目录移到新目录中

2024-03-29 12:49:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

注意:我搜索的论坛返回了如何将单个子目录中的所有文件移动到新目录的解决方案。具体如下:

  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


Tags: 文件csvtofromhttps目录脚本com
2条回答

假设CSV文件如下所示:

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

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

^{pr2}$

这样的方法可能对你有用:

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文件只包含以逗号分隔的路径,并且所有这些文件都存在。在

相关问题 更多 >