[英]Move certain files from specific subdirectories into a new directory
How do I move only certain files (not all files), from specific subdirectories (not all subdirectories), into a new directory? 如何仅将某些文件(不是所有文件)从特定子目录(不是所有子目录)移动到新目录中?
The files that need to be moved have been listed in a CSV file and are about 85,000 in number. CSV文件中列出了需要移动的文件,数量约为85,000。 They have been mentioned with their absolute paths.
他们以绝对的路径被提及。 All the files possess the same extension, ie,
.java
. 所有文件都具有相同的扩展名,即
.java
。 The number of specific subdirectories is about 13,000. 特定子目录的数量约为13,000。
Is there a Python script (preferred) or a Shell script to do this? 是否有Python脚本(首选)或Shell脚本来执行此操作?
NB: The forums that I searched on returned solutions on how to move all files from within a single subdirectory into a new directory. 注意:我搜索过的论坛返回了有关如何将所有文件从单个子目录移动到新目录的解决方案。 They are mentioned below:
它们在下面提到:
https://www.daniweb.com/programming/software-development/threads/473187/copymove-all-sub-directories-from-a-folder-to-another-folder-using-python https://www.daniweb.com/programming/software-development/threads/473187/copymove-all-sub-directories-from-a-folder-to-another-folder-using-python
http://pythoncentral.io/how-to-copy-a-file-in-python-with-shutil/ http://pythoncentral.io/how-to-copy-a-file-in-python-with-shutil/
Filter directory when using shutil.copytree? 使用shutil.copytree时过滤目录?
https://unix.stackexchange.com/questions/207375/copy-certain-files-from-specified-subdirectories-into-a-separate-subdirectory https://unix.stackexchange.com/questions/207375/copy-certain-files-from-specified-subdirectories-into-a-separate-subdirectory
Something like this might work for you: 这样的事情可能适合您:
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')
This assumes that your CSV file only contains paths, delimited by commas, and all of those files exist. 假定您的CSV文件仅包含用逗号分隔的路径,并且所有这些文件都存在。
Assuming that your CSV file looks like this: 假设您的CSV文件如下所示:
George,/home/geo/mtvernon.java,Betsy
Abe,/home/honest/gettys.java,Mary
You could move the files using this shell command: 您可以使用以下shell命令移动文件:
$ cut -d, -f2 < x.csv | xargs -I '{}' mv '{}' /home/me/new-directory
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.