简体   繁体   中英

Is there a way to copy files from one folder to another using a subtext of that file name in python?

I have a list of all files available in a local folder:

['13.643636,100.346960_5',
 '13.643636,100.350394_6',
 '13.643636,100.353828_7',
 '13.643636,100.357262_8',
 '13.643636,100.360696_9',
 '13.643636,100.364130_10',
 '13.643636,100.367564_11',
 '13.643636,100.370998_12',
 '13.643636,100.374432_13',
 '13.643636,100.377866_14',
 '13.643636,100.381300_15',
 '13.643636,100.384734_16']

and my folder has images for example '13.643636,100.346830_5.png', '13.643636,100.350664_6.png', '13.643636,100.353938_7.png', '13.643636,100.357452_8.png', '13.643636,100.360786_9.png', etc.

The values denote lat_long_sequence. Sequence is the value after an underscore.

Now, I have 10000s of these photos but the lat and long in the list do not match to those in the folder but the sequence of which matches perfectly.

Is there a way, I can use this sequence to find all the images in a folder and copy it to another folder locally?

I have a folder thats has all the images called 'my_folder'. My list is 'my_list' and the folder I want to copy the images to as per 'my_list' is 'proc_folder'.

Appreciate any help.

Thanks.

Assuming

  • proc_folder already exists
  • my_folder and proc_folder are complete paths to those folders OR are in the same folder as your current working directory

In case you want to create the list by python, use:

import os
dir_list = os.listdir(`my_folder`)
image_list = [file for file in dir_list if '.png' in file]

Then you can copy all those files:

import shutil
for i_string in my_list:
   i_file = i_string + '.png'
   shutil.copyfile('my_folder\' + i_file, 'proc_folder' + i_file)

Get the seq from my_list and store it in seq_list. Then move the files from my_folder which contain the seq in seq_list

Code:

import shutil
import os

my_list = ['13.643636,100.346960_5',
 '13.643636,100.350394_6',
 '13.643636,100.353828_7',
 '13.643636,100.357262_8',
 '13.643636,100.360696_9',
 '13.643636,100.364130_10',
 '13.643636,100.367564_11',
 '13.643636,100.370998_12',
 '13.643636,100.374432_13',
 '13.643636,100.377866_14',
 '13.643636,100.381300_15',
 '13.643636,100.384734_16']
 
seq_list = ['_' + ele.split('_')[1] for ele in my_list]
# ['_5', '_6', '_7', '_8', '_9', '_10', '_11', '_12', '_13', '_14', '_15', '_16']

for entry in os.scandir('my_folder'):
    if entry.is_file() and entry.name.split('_')[1] in seq_list:
        shutil.copyfile(entry.path + entry.name, 'dest_folder')
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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